pandas笔记

pandas常用命令整理。

重命名列名

1
2
3
4
# 命名一列
df.rename(columns={df.columns[2]: "A"}, inplace=True)
# 命名全部
df.columns = ['A', 'B', 'C']

删除行列

1
2
3
4
5
6
7
8
9
# 删除一行
df.drop(0[, inplace=False])
# 删除多行
df.drop([a,b])
# 删除一列
del df['A']
df.drop('A')
# 删除多列
df.drop(['A','B'])

排序

1
2
df.sort_values('A'[,inplace=True])
df.sort_values(by=['a','c'])

去重

1
2
df.duplicated() #返回true or false
df.drop_duplicates(['column'])

连接数据库

1
2
3
4
5
6
7
8
9
import pymysql # 其他数据库也可以,创建数据库连接就行
import pandas as import pd

db = pymysql.connect(host='', port='', user='', passwd='', db='')
# 读取数据
query = "" # 查询语句
df = pd.read_sql(sql=query, con=db)
# 存储数据
df.to_sql('table_name', con=db, if_exists='append', index=False) # if_exists: fail, append, replace

写入excel(多sheet)

1
2
3
4
writer = pd.ExcelWriter('t.xlsx')
df1.to_excel(writer,'sheet1',index=0)
df2.to_excel(writer,'sheet2',index=0)
writer.save()

透视表

1
pd.pivot_table(dataframe,index='c1', values=['c2','c3','c4'], aggfunc={'c2':sum,'c3':lambda x: len(x.unique()),'c4':len}, margins=True,margins_name='total')

环比

1
2
# 计算环比
d2 = (dt-dt_last).reindex(dt.index)

切分类别

1
pd.cut([sequence], bins, labels)

条件替换

1
2
3
4
5
6
7
8
9
# Replace values where the condition is False
df.where(cond, other, inplace)
# Replace values where the condition is True
df.mask(cond, other, inplace)
# 将`nan`替换成0
cond = df.isna()
df.where(~cond, 0)
# or
df.mask(cond, 0)
-------------本文结束感谢您的阅读-------------
0%