记录一些常用的pandas数据操作方法
#导入pandas包
import pandas as pd
# 读取
df = pd.read_csv("path", encoding="utf-9")
df = pd.read_excel("path", sheet_name="Sheet1")
# 保存
df = df.sample(1000, random_state=42)
df = df[["rowkey", "content", "title"]]
df.to_excel("是否需要改写标注.excel", index_label=False)
可以使用loc或at来在指定的行和列中填充数据。
import pandas as pd
# 创建一个简单的DataFrame
df = pd.DataFrame({
'A': ['foo', 'bar', 'baz'],
'B': ['one', 'two', 'three']
})
# 添加新的列,并在指定的行中填充数据
df.loc[0, 'C'] = 'new1'
df.loc[1, 'C'] = 'new2'
df.loc[2, 'C'] = 'new3'
df.at[0, 'C'] = 'new1'
df.at[1, 'C'] = 'new2'
df.at[2, 'C'] = 'new3'
print(df)
df['column_name'] = 'xxxx'
data = {
"A": [1, 2, 3, 4, 5],
"B": [6, 7, 8, 9, 10]
}
df = pd.DataFrame(data)
filtered_df = df.drop(rows_to_remove, axis=0)
可选固定随机种子
test_df = df.sample(n=10, random_state=42)
# 扩展,使用随机抽样方法完全抽样打乱数据
# frac是抽样比例,抽样完记得重置下样本编号
df = df.sample(frac=1).reset_index(drop=True)
df = df.reset_index(drop=True)
df = df.drop_duplicates(subset=["col_name"])
ascending指定生序还是降序
df = pd.DataFrame(datas).sort_values(["col_name"], ascending=False)
可以对任意列的元素进行简单的数学运算
df["col3"] = df["col1"] + df["col2"]
df["col3"] = df["col1"] - df["col2"]
df["col3"] = df["col1"] * df["col2"]
df["col3"] = df["col1"] / df["col2"]
dfs=[df1,df2,df3]
df = pd.concat(dfs, axis=0)
df = df[(df['col1'] > 1000) & (df['col2'] > 0) & (df['col3'] < 1)]
按照col1-col3的元素进行分组,分组过程,组内col4和col5列做求和运算
df = df.groupby(["col1", "col2", "col3"]).agg(col6=pd.NamedAgg(column="col4", aggfunc=np.sum),
col7=pd.NamedAgg(column="col5", aggfunc=np.sum)).reset_index()