Python pandas dataframe 使用键将 2 行合并为 1
Python pandas dataframe merge 2 rows into one with keys
我有 2 个数据框,每个都有一行,具有相同的列:
df1 = feat_1 feat_2 ... feat_n a b c d ... z
A B N 1 2 3 4 9
df2 = feat_1 feat_2 ... feat_n a b c d ... z
A B N 5 6 1 8 3
feat_1.. feat_n
与 2 行相同,应连接其他列,以便新行为:
new_df = feat_1 feat_2 ... feat_n a_1 a_2 b_1 b_2 c_1 c_2 d_1 d_2 ... z_1 z_2
A B N 1 5 2 6 3 1 4 8 9 3
最好的方法是什么?
只需使用合并命令:
new_df = pd.merge(df1, df2, how="inner", on =["feat_1", 'feat_2', 'feat_n'], suffixes=('_1','_2'))
输入:
df1
feat_1 feat_2 feat_n a b
0 A B N 1 2
df2
feat_1 feat_2 feat_n a b
0 A B N 3 4
代码:
new_df = pd.merge(df1, df2, how="inner", on =["feat_1", 'feat_2', 'feat_n'], suffixes=('_1','_2'))
打印:
feat_1 feat_2 feat_n a_1 b_1 a_2 b_2
0 A B N 1 2 3 4
我有 2 个数据框,每个都有一行,具有相同的列:
df1 = feat_1 feat_2 ... feat_n a b c d ... z
A B N 1 2 3 4 9
df2 = feat_1 feat_2 ... feat_n a b c d ... z
A B N 5 6 1 8 3
feat_1.. feat_n
与 2 行相同,应连接其他列,以便新行为:
new_df = feat_1 feat_2 ... feat_n a_1 a_2 b_1 b_2 c_1 c_2 d_1 d_2 ... z_1 z_2
A B N 1 5 2 6 3 1 4 8 9 3
最好的方法是什么?
只需使用合并命令:
new_df = pd.merge(df1, df2, how="inner", on =["feat_1", 'feat_2', 'feat_n'], suffixes=('_1','_2'))
输入:
df1
feat_1 feat_2 feat_n a b
0 A B N 1 2
df2
feat_1 feat_2 feat_n a b
0 A B N 3 4
代码:
new_df = pd.merge(df1, df2, how="inner", on =["feat_1", 'feat_2', 'feat_n'], suffixes=('_1','_2'))
打印:
feat_1 feat_2 feat_n a_1 b_1 a_2 b_2
0 A B N 1 2 3 4