python处理数据一些小tips

字符串操作指南
本文介绍了Python中字符串的操作方法,包括str.split()函数的使用,详细解释了如何通过指定分隔符和最大拆分次数来分割字符串。同时,还深入探讨了字符串格式化函数format()的应用,演示了多种参数设置方式。

str.split(separator, maxsplit)

separator : The is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.

maxsplit : It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then there is no limit.

format 格式化函数

格式化字符串 

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

也可以设置参数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

字典遍历 使用迭代器 

for i, (k, v) in enumerate(mydict.items()):
    # your stuff
mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
    print("index: {}, key: {}, value: {}".format(i, k, v))

# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b

 解释:

  • enumerate returns an iterator object which contains tuples in the format: [(index, list_element), ...]
  • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...]
  • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]
Python有许多用于数据处理的库,以下是一些常用的库: ### NumPy NumPy(Numerical Python)是Python科学计算的基础库,提供了高效的多维数组对象以及处理这些数组的函数。它可以用于存储和处理大型矩阵,比Python自身的嵌套列表结构要高效得多。 ```python import numpy as np # 创建一个一维数组 arr = np.array([1, 2, 3, 4, 5]) print(arr) ``` ### Pandas Pandas是一个强大的数据处理和分析库,提供了DataFrame和Series等数据结构,方便进行数据的读取、清洗、转换和分析。它支持从多种文件格式(如CSV、Excel、SQL数据库等)中读取数据。 ```python import pandas as pd # 从CSV文件中读取数据 data = pd.read_csv('data.csv') print(data.head()) ``` ### SciPy SciPy是一个用于数学、科学和工程计算的库,它建立在NumPy之上,提供了许多高级的科学计算功能,如优化、积分、插值、信号处理等。 ```python from scipy import optimize # 定义一个简单的函数 def f(x): return x**2 + 3*x + 2 # 寻找函数的最小值 result = optimize.minimize(f, 0) print(result.x) ``` ### Matplotlib Matplotlib是一个用于绘制图表和可视化数据的库,它可以创建各种类型的图表,如折线图、柱状图、散点图等。 ```python import matplotlib.pyplot as plt import numpy as np # 生成数据 x = np.linspace(0, 10, 100) y = np.sin(x) # 绘制折线图 plt.plot(x, y) plt.show() ``` ### Seaborn Seaborn是基于Matplotlib的高级数据可视化库,它提供了更美观、更简洁的统计图形接口,能够创建各种复杂的统计图表。 ```python import seaborn as sns import pandas as pd # 加载示例数据tips = sns.load_dataset('tips') # 绘制散点图 sns.scatterplot(x='total_bill', y='tip', data=tips) plt.show() ``` ### Scikit-learn Scikit-learn是一个用于机器学习的库,提供了各种机器学习算法和工具,如分类、回归、聚类、降维等。在数据处理中,它也可以用于数据的预处理和特征工程。 ```python from sklearn.preprocessing import StandardScaler import numpy as np # 生成一些数据 data = np.array([[1, 2], [3, 4], [5, 6]]) # 数据标准化 scaler = StandardScaler() scaled_data = scaler.fit_transform(data) print(scaled_data) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值