Day24学习总结
前言
今天学的的内容为删除数据,行索引操作及pands中的部分函数
一、删除数据
通过drop方法删除 DataFrame 中的数据,默认情况下,drop() 不会修改原 DataFrame,而是返回一个新的 DataFrame。
- 关键参数
labels 单个标签或列表。根据axis改变。
axis axis=0 或 axis=‘index’ 表示删除行,axis=1 或 axis=‘columns’ 表示删除列。
inplace 如果为 True,则直接修改原 DataFrame,而不是返回一个新的 DataFrame。
#示例
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'score': [85, 90, 88]
}
df = pd.DataFrame(data)
df = df.drop('Alice',axis=0)#删除Alice行的数据
df.drop('name',axis=1,inplace=True)#删除name列的数据在原数据上修改
二、行索引操作
1.loc
df.loc[] 只能使用标签索引,不能使用整数索引。同时其是前闭后闭
- DataFrame.loc[row_indexer, column_indexer]
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data)
df.loc[1,'A']#取行索引为1的‘A’列数据
df.loc[:,'A']#取‘A’列数据
2.iloc
df.iloc[] 方法用于基于位置的索引。
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [23, 25, 22, 24, 23],
'score': [85, 90, 88, 92, 87]
}
df = pd.DataFrame(data)
df.iloc[0]#取索引为0行的数据
df.iloc[1,2:]#取索引为1行同时列索引为2及之后的数据
3.切片多行选取
通过切片的方式进行多行数据的选取
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data)
df[0:3]#取前三行的数据
4.添加数据行
loc方法添加新行
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data)
df.loc[4] = [17, 18, 19]
concat拼接
- 关键参数
- objs: 要连接的 DataFrame 或 Series 对象的列表或字典。
- axis: 指定连接的轴,0 或 ‘index’ 表示按行连接,1 或 ‘columns’ 表示按列连接。
- ignore_index: 如果为 True,则忽略原始索引并生成新的索引。
- join: 指定连接方式,‘outer’ 表示并集(默认),‘inner’ 表示交集。
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df2 = pd.DataFrame({
'A': [7, 8, 9],
'B': [10, 11, 12]
})
df1 = pd.DataFrame(data)
df_c = pd.concat([df1,df2],axis=0)#按行方向进行拼接2中没有的c列会用NaN填充
print(df_c)
df_c = pd.concat([df1,df2],axis=1)#按列方向进行拼接,没有的数据会用NaN填充
print(df_c)
join案列
df1 = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
}, index=[0, 1, 2])
df2 = pd.DataFrame({
'A': [7, 8, 9],
'B': [10, 11, 12],
'D': [13, 14, 15]
}, index=[1, 2, 3])
# 按行合并,只匹配column相同的列,行被堆叠
result = pd.concat([df1, df2], axis=0, join='inner')#D列会被删去
print(result)
# 按列合并,只匹配index相同的行,列被堆叠
result = pd.concat([df1, df2], axis=1, join='inner')#没有相同的行索引的行会被删去
print(result)
二、函数
- 常用的函数:
- count() 统计某个非空值的数量
- sum() 求和
- mean() 求均值
- median() 求中位数
- std() 求标准差
- min() 求最小值
- max() 求最大值
- abs() 求绝对值
- prod() 求所有数值的乘积
此处便不一一举例用到时直接使用即可。
1.重置索引
reindex
- DataFrame.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=np.nan, limit=None, tolerance=None)
大多数的参数都与之前的意思差不多因此便不一一解释。
data = {
'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8],
'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data,index=['a','b','c','d'])
df1 = df.reindex(['A','B','C','D'],axis=1,method='ffill')#增加了D列同时用前面的数来填充
print(df1)
df2 = df.reindex(['a','b','c','e','d'],axis=0)#增加了e行
print(df2)
df3 =df.reindex(columns=['A','B','C','D'],index=['a','b','c','d','e'],fill_value=0) #增加了D列和e行 同时用0进行填充
print(df3)

678

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



