Use*_*090 7 python merge join concat pandas
我试图将SQL查询转换为python.sql语句如下:
select * from table 1
union
select * from table 2
union
select * from table 3
union
select * from table 4
Run Code Online (Sandbox Code Playgroud)
现在我有4个数据帧中的那些表,df1, df2, df3, df4
我想结合4个pandas数据帧,它将匹配结果与sql查询相同.我很困惑使用哪种操作相当于sql union?提前致谢!!
注意:所有数据帧的列名都相同.
IIUC 您可以使用merge
并按matching_col
所有数据帧的列进行连接:
import pandas as pd
# Merge multiple dataframes
df1 = pd.DataFrame({"matching_col": pd.Series({1: 4, 2: 5, 3: 7}),
"a": pd.Series({1: 52, 2: 42, 3:7})}, columns=['matching_col','a'])
print df1
matching_col a
1 4 52
2 5 42
3 7 7
df2 = pd.DataFrame({"matching_col": pd.Series({1: 2, 2: 7, 3: 8}),
"a": pd.Series({1: 62, 2: 28, 3:9})}, columns=['matching_col','a'])
print df2
matching_col a
1 2 62
2 7 28
3 8 9
df3 = pd.DataFrame({"matching_col": pd.Series({1: 1, 2: 0, 3: 7}),
"a": pd.Series({1: 28, 2: 52, 3:3})}, columns=['matching_col','a'])
print df3
matching_col a
1 1 28
2 0 52
3 7 3
df4 = pd.DataFrame({"matching_col": pd.Series({1: 4, 2: 9, 3: 7}),
"a": pd.Series({1: 27, 2: 24, 3:7})}, columns=['matching_col','a'])
print df4
matching_col a
1 4 27
2 9 24
3 7 7
Run Code Online (Sandbox Code Playgroud)
解决方案1:
df = pd.merge(pd.merge(pd.merge(df1,df2,on='matching_col'),df3,on='matching_col'), df4, on='matching_col')
set columns names
df.columns = ['matching_col','a1','a2','a3','a4']
print df
matching_col a1 a2 a3 a4
0 7 7 28 3 7
Run Code Online (Sandbox Code Playgroud)
解决方案2:
dfs = [df1, df2, df3, df4]
#use built-in python reduce
df = reduce(lambda left,right: pd.merge(left,right,on='matching_col'), dfs)
#set columns names
df.columns = ['matching_col','a1','a2','a3','a4']
print df
matching_col a1 a2 a3 a4
0 7 7 28 3 7
Run Code Online (Sandbox Code Playgroud)
但如果您只需要连接数据帧,请concat
与通过参数重置索引一起使用ignore_index=True
:
print pd.concat([df1, df2, df3, df4], ignore_index=True)
matching_col a
0 4 52
1 5 42
2 7 7
3 2 62
4 7 28
5 8 9
6 1 28
7 0 52
8 7 3
9 4 27
10 9 24
11 7 7
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20442 次 |
最近记录: |