先通过字典创建一个DateFrame
import pandas as pd
import numpy as np
data=dict.fromkeys(['first','second','third'])
for i in data:
i=[]
for i in range(20):
data['first'].append(i)
data['second'].append(i*i)
data['third'].append(2*i+1)
df=pd.DataFrame(data)
建议先help(pd.concat)查看有哪些参数和用法
ignore_index=True
keys=[‘s1’, ‘s2’,]
names=[‘Series name’, ‘Row ID’]
#axis=0列对齐,=1行对齐,空缺处以NaN补齐
pd.concat([df[:3],df[5:8]],axis=1,keys=['s1','s2'])
s1 s2
first second third first second third
0 0.0 0.0 1.0 NaN NaN NaN
1 1.0 1.0 3.0 NaN NaN NaN
2 2.0 4.0 5.0 NaN NaN NaN
5 NaN NaN NaN 5.0 25.0 11.0
6 NaN NaN NaN 6.0 36.0 13.0
7 NaN NaN NaN 7.0 49.0 15.0
#keys标明新的DateFrame中最外层的分层索引
pd.concat([df[:3],df[5:8]],keys=['s1','s2'])
first second third
s1 0 0 0 1
1 1 1 3
2 2 4 5
s2 5 5 25 11
6 6 36 13
7 7 49 15
#ignore_index=True忽略原有index索引,重新生成index
pd.concat([df[:3],df[2:5]],ignore_index=True)
first second third
0 0 0 1
1 1 1 3
2 2 4 5
3 2 4 5
4 3 9 7
5 4 16 9
df=pd.DataFrame(np.arange(12).reshape(3,4))
df1=pd.DataFrame(np.arange(15).reshape(3,5))
df[:2].append([df1,])#ignore_index=True也是重新生成index索引
0 1 2 3 4
0 0 1 2 3 NaN
1 4 5 6 7 NaN
0 0 1 2 3 4.0
1 5 6 7 8 9.0
2 10 11 12 13 14.0
比如读取两个csv文件,现在有一个需求,两个csv中某些column相同,然后要分别对不同的数据进行操作,这个时候就要用到类似数据库的链接操作功能
内部链接:从两个数据表中提取数据,规定的列上存在相匹配的值,相应的数据就会被组合起来。inner
外部链接:不要求匹配,可以返回更多数据.outer
左/右外链接
left是左表,right是右表,right对齐left
on=[key1,key2,]列名,有待对齐的列名
how数据融合的方式,默认inner只保留公共部分,可选left(保留左表所有数据)、right(类似)、outer(保留两个表所有数据)
sort表示是否排序
df=pd.DataFrame({'A':['a0','a1','a2','a0'],'B':['b0','b0','b1','b2'],'C':['c0','c1','c1','c2']})
df1=pd.DataFrame({'A':['a1','a0','a2','a0'],'B':['b0','b1','b1','b2'],'C':['c1','c1','c1','c2']})
result=pd.merge(df,df1,on=['A'])
#对A匹配
result
A B_x C_x B_y C_y
0 a0 b0 c0 b1 c1
1 a0 b0 c0 b2 c2
2 a0 b2 c2 b1 c1
3 a0 b2 c2 b2 c2
4 a1 b0 c1 b0 c1
5 a2 b1 c1 b1 c1
#以df1为准,对AC匹配保留df1信息,并对结果排序
pd.merge(df,df1,how='right',sort=True,on=['A','C'])
A B_x C B_y
0 a0 NaN c1 b1
1 a0 b2 c2 b2
2 a1 b0 c1 b0
3 a2 b1 c1 b1
#indicator参数(默认False),增加一列_merge(可取both,left/right_only),更直观显示整合结果
pd.merge(df,df1,on=['A','B'],how='outer',indicator=True)
A B C_x C_y _merge
0 a0 b0 c0 NaN left_only
1 a1 b0 c1 c1 both
2 a2 b1 c1 c1 both
3 a0 b2 c2 c2 both
4 a0 b1 NaN c1 right_only
列名要不相同,否则ValueError: columns overlap but no suffix specified
df1.columns=['A1','B1','C1']
df.join(df1)
A B C A1 B1 C1
0 a0 b0 c1 a1 b0 c1
1 a1 b0 c1 a0 b1 c1
2 a2 b1 c1 a2 b1 c1
3 a0 b2 c2 a0 b2 c2
on参数,应用中如果右表的索引值正是左表的某一列的值,这时可以通过将 右表的索引 和 左表的列 对齐合并这样灵活的方式进行合并。
#修改df1的index
df1.index=['b0','b0','b1','b2']
df1
A1 B1 C1
b0 a1 b0 c1
b0 a0 b1 c1
b1 a2 b1 c1
b2 a0 b2 c2
df.join(df1,on='B')
A B C A1 B1 C1
0 a0 b0 c1 a1 b0 c1
0 a0 b0 c1 a0 b1 c1
1 a1 b0 c1 a1 b0 c1
1 a1 b0 c1 a0 b1 c1
2 a2 b1 c1 a2 b1 c1
3 a0 b2 c2 a0 b2 c2
PANDAS 数据合并与重塑join/merge篇