pandas常用句

做研究助理的过程中使用pandas做数据分析比较多,记录下使用最频繁的语句。

输入输出

1
2
3
4
5
6
# txt:read_table
# xlsx,xls:read_excel
# csv:read_csv

pd=pd.read_excel('/content/drive/MyDrive/notebook/socio/input/lbs.xlsx')
tmp.to_excel('/content/drive/MyDrive/notebook/socio/output/tmp.xlsx')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from google.colab import drive
drive.mount('/content/drive')
#rename
test.rename(columns={'终点ID':'起点网格ID'}, inplace = True)
#aggregation
work_agg=work.groupby(['town']).agg({'人数': [np.sum]})
#output
work_agg.to_csv('work_agg.txt',sep='\t', index=False)
#drop
tmp.drop(['B', 'C'], axis=1)
#merge
# merge一定要注意选择没有重复值的列作
result_inner = pd.merge(cencus_lbs,
commute,
left_on='街镇',
right_on='town',
how='inner')
#add column

df['home_ratio'] = df.apply(lambda x: function(x["home"], x["pop20"]), axis=1)
df['com_17_o']= df.apply(lambda x: function(x["com_17_o"], x["pop20"]), axis=1)
df['com_17_d']= df.apply(lambda x: function(x["com_17_d"], x["pop20"]), axis=1)

df['com_21_o']= df.apply(lambda x: function(x["com_21_o"], x["pop20"]), axis=1)
df['com_21_d']= df.apply(lambda x: function(x["com_21_d"], x["pop20"]), axis=1)
return df

#add colunm2
def ses1(input):
df = input

conditions = [
((df['专业技术人员 ']+df['管理者和企业主']) >= (df['个体经营业者']+df['文职人员']+df['服务人员']))&((df['专业技术人员 ']+df['管理者和企业主']) >= df['生产操作人员']),
((df['个体经营业者']+df['文职人员']+df['服务人员']) >= (df['专业技术人员 ']+df['管理者和企业主']) ) & ((df['个体经营业者']+df['文职人员']+df['服务人员'])>= df['生产操作人员']),
(df['生产操作人员']>(df['专业技术人员 ']+df['管理者和企业主']) )&( df['生产操作人员']>(df['个体经营业者']+df['文职人员']+df['服务人员']))
]
values = [1,2,3]
df['ses_level'] = np.select(conditions, values)
return df

Geopandas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#geopandas
!apt install libspatialindex-dev
!pip install rtree
!pip install geopandas
import geopandas as gpd
#read data
subdis=gpd.read_file('/content/drive/MyDrive/notebook/socio/input/subdistrict.shp')

#转geopandas格式输出shp
geometry = [Point(xy) for xy in zip(df.Lon, df.Lat)]
df = df.drop(['Lon', 'Lat'], axis=1)
gdf = GeoDataFrame(df, crs="EPSG:4326", geometry=geometry)

gdf.to_file("countries.shp")
1
2
3
4
# colab 文件夹操作
fileList=os.listdir('/content/drive/MyDrive/LBS/Fishnet/Centre')
fileList.sort()
odfileList = gffp()
1
2
3
4
5
#字符操作
print(df[df['name'].str.endswith('e')])
#判空
print(arr[pd.isna(arr['numTest'])==True])

txt合并

1
2
3
4
5
6
7
8
9
10
11
12
13
import os

path = r"/content/drive/MyDrive/LBS/Fishnet/Centre"
files = os.listdir(path)
txts = pd.DataFrame()
for file in files:
position = path + os.sep + file
print(position)
data = pd.read_csv(position, sep='\\s+')
txts = pd.concat([txts, data])

txts.to_csv('data.csv', encoding='utf-8', index=False)

Pandas vs SQL

groupby

1
2
3
4
SELECT "性别", count(*)FROM dfGROUP BY 性别;
SELECT 星期几, AVG(小费), COUNT(*)FROM dfGROUP BY 星期几;
SELECT 是否吸烟, 星期几, COUNT(*), AVG(小费)FROM tipsGROUP BY 是否吸烟, 星期几;

1
2
3
4
5
6
7
df.groupby('性别').size()
df.groupby('性别').count()
df.groupby('性别')["总费用"].count()
#agg()允许将字典传递给分组的DataFrame,从而指示要应用于特定列的函数。
df.groupby('星期几').agg({'小费': np.mean, '星期几': np.size})
#通过将一列列传递给方法,来完成按多个列分组groupby()
df.groupby(['是否吸烟', '星期几']).agg({'小费': [np.size, np.mean]})

连接

mysql

JOIN 按照功能大致分为如下三类:

  • INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
  • LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
  • RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
pandas

可以使用join()或merge()执行JOIN。 默认情况下,join()将在其索引上联接DataFrame。 每个方法都有参数,可让指定要执行的联接类型(LEFT,RIGHT,INNER,FULL)或要联接的列(列名或索引)。推荐使用merge()函数。

1
2
3
4
5
6
7
8
#inner join 内连接
SELECT *FROM df1INNER JOIN df2 ON df1.key = df2.key;
#left outer join左连接
SELECT *FROM df1LEFT OUTER JOIN df2 ON df1.key = df2.key;
#right join右连接
SELECT *FROM df1RIGHT OUTER JOIN df2 ON df1.key = df2.key;
#full join全连接
#MySQL中不支持全连接,一般使用union完成
1
2
3
4
5
6
7
8
#inner join 内连接 
pd.merge(df1, df2, on='key')
#left outer join左连接
pd.merge(df1, df2, on='key', how='left')
#right join右连接
pd.merge(df1, df2, on='key', how='right')
#full join全连接
pd.merge(df1, df2, on='key', how='outer')

性能对比

在Pandas官方文档中提出会比R中base::merge.data.frame函数快,因为其对于DataFrame的精心的算法设计和内部数据布局

但是软件开发中似乎普遍使用SQL,据说是到Terabyte这种数量级的话pandas是没有办法操作的,但由于自己目前操作的数据是txt格式,几个G,导入自己电脑MySQL会出现内存不够的情况,所以直接使用pandas.DataFame似乎更方便。

聚合与连接操作息息相关

尽量将连接作为最后操作

References

常用方法对比实现:https://www.finclip.com/news/f/32239.html

Pandas官方文档相关内容:https://pandas.pydata.org/docs/user_guide/merging.html?highlight=merge#database-style-dataframe-or-named-series-joining-merging