Day25-26学习总结
一、DataFrame遍历
- 直接使用for循环进行遍历只能遍历到列标签
df = pd.DataFrame({
'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
})
for i in df:
print(i)#只会输出one和two
- itertuples(),返回一个行元素的元组
data = {
'A': [1, 2, 3],
'B': [4, 5, 6],
'C': [7, 8, 9]
}
df = pd.DataFrame(data)
# index参数:如果为False,则遍历后的元组中过滤掉行索引信息
for row in df.itertuples(index=False):# index参数:如果为False,则遍历后的元组中过滤掉行索引信息
print(row)#此处为一个元组
for i in row:#再取出元组中的每数据
print(i)
- items(),返回列索引标签和列数据的迭代器
for idx, value in df.items():
print(idx, value)
- index和columns属性遍历
# 遍历index
for row in df.index:
# 遍历columns:
for col in df.columns:
print(df.loc[row, col])
二、排序
- sort_index 方法用于对 DataFrame 或 Series 的索引进行排序。
- sort_values 方法用于根据一个或多个列的值对 DataFrame 进行排序。
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=‘quicksort’, na_position=‘last’)
by:列的标签或列的标签列表。指定要排序的列。
ascending:布尔值或布尔值列表,指定是升序排序(True)还是降序排序(False)。可以为每个列指定不同的排序方向。
其余参数与其他函数的意义相同
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [25, 30, 25, 35, 30],
'Score': [85, 90, 80, 95, 88]
})
# 按Age列排序
df1 = df.sort_values(by=['Age'])
print(df1)
# 按Age和Score排序,默认是升序排序
# 如果Age列有相同的值,则Score再按照升序排序
df2 = df.sort_values(by=['Age', 'Score'])
print(df2)
三、去重
drop_duplicates(by=None, subset=None, keep=‘first’, inplace=False)
Series.drop_duplicates(keep=‘first’, inplace=False)
keep:指定如何处理重复项。可以是:
‘first’:保留第一个出现的重复项(默认值)。
‘last’:保留最后一个出现的重复项。
False:删除所有重复项。
四、分组
- groupby用于对数据进行分组操作
data = {
'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]
}
df = pd.DataFrame(data)
# 按A列分组
grouped = df.groupby('A')
print(list(grouped))
# 按A列分组,然后计算每个分组内C列的平均值
df1 = df.groupby('A')['C'].mean()
print(df1)
- 通过tranform将计算结果进行转换,保存到DataFrame中
mean = df.groupby('A')['C'].transform('mean')
df['C_Mean'] = mean
print(df)
# 分组求出均值后将均值分配到对应的每一行数据上
- filter() 函数可以实现数据的筛选,该函数根据定义的条件过滤数据并返回一个新的数据集
mean = df.groupby('A')['C'].transform('mean')
df['C_Mean'] = mean
print(df)
# 分组求出均值后将均值分配到对应的每一行数据上
四、合并
- pandas.merge(left, right, how=‘inner’, on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=(‘_x’, ‘_y’), copy=True, indicator=False, validate=None)
left:左侧的 DataFrame 对象。
right:右侧的 DataFrame 对象。
how:合并方式,可以是 ‘inner’、‘outer’、‘left’ 或 ‘right’。默认为 ‘inner’。
on:用于连接的列名。如果未指定,则使用两个 DataFrame 中相同的列名。
left_on 和 right_on:分别指定左侧和右侧 DataFrame 的连接列名。
left_index 和 right_index:布尔值,指定是否使用索引作为连接键。
left = pd.DataFrame({
'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']
})
right = pd.DataFrame({
'key': ['K0', 'K1', 'K2', 'K4'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']
})
# 左连接,以左侧表为准
result = pd.merge(left, right, on='key', how='left')
print(result)
五、随机抽样
- DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
n:要抽取的行数
frac:抽取的比例,比如 frac=0.5,代表抽取总体数据的50%
replace:布尔值参数,表示是否以有放回抽样的方式进行选择,默认为 False,取出数据后不再放回
df = pd.DataFrame({
"company": ['百度', '阿里', '腾讯'],
"salary": [43000, 24000, 40000],
"age": [25, 35, 49]
})
# 随机抽取2行
df1 = df.sample(n=2, axis=0, random_state=1)
print(df1)
# 随机抽取1列
df2 = df.sample(n=1, axis=1)
六、空值处理
-
isnull()用于检测 DataFrame 或 Series 中的空值,返回一个布尔值的 DataFrame 或 Series。
-
notnull()用于检测 DataFrame 或 Series 中的非空值,返回一个布尔值的 DataFrame 或 Series。
is_null = df.isnull()
print(is_null)
# 检测非空值
not_null = df.notnull()
print(not_null)
- fillna() 方法用于填充 DataFrame 或 Series 中的空值。
# 用 0 填充空值
df_filled = df.fillna(0)
print(df_filled)
- dropna() 方法用于删除 DataFrame 或 Series 中的空值。
# 删除包含空值的行
df_dropped = df.dropna()
print(df_dropped)
# 删除包含空值的列
df_dropped = df.dropna(axis=1)
print(df_dropped)
七、读取CSV文件
- to_csv()将DataFrame输出为csv文件
- read_csv()读取csv文件
八、绘图
Pandas对 plot() 方法做了简单的封装
只用 pandas 绘制图片可能可以编译,但是不会显示图片,需要使用 matplotlib 库,调用 show() 方法显示图形。
# 绘制折线图
df.plot(kind='line')
# 显示图表
plt.show()
# 绘制柱状图
df.plot(kind='bar')
# 显示图表
plt.show()
# 绘制直方图
df['A'].plot(kind='hist')
# 显示图表
plt.show()
# 绘制散点图
df.plot(kind='scatter', x='A', y='B')
# 显示图表
plt.show()
# 绘制饼图
series.plot(kind='pie', autopct='%1.1f%%')

2万+

被折叠的 条评论
为什么被折叠?



