【发布时间】:2021-12-27 10:08:09
【问题描述】:
我在连接两个不同长度的数据帧时遇到问题。以下是问题:
df1 =
emp_id emp_name counts
1 sam 0
2 joe 0
3 john 0
df2 =
emp_id emp_name counts
1 sam 0
2 joe 0
2 joe 1
3 john 0
我的预期输出是: 请注意,我的期望不是将 2 个数据帧合并为一个,但我想并排连接两个数据帧并突出显示差异,如果在一个 df 中存在重复行,例如 df2,则相应的df1 的行应显示为 NaN/blank/None 任何 Null 类型的值
Expected_output_df =
df1 df2
empId emp_name counts emp_id emp_name counts
1 sam 0 1 sam 0
2 joe 0 2 joe 0
NaN NaN NaN 2 joe 1
3 john 0 3 john 0
而我得到如下输出:
actual_output_df = pd.concat([df1, df2], axis='columns', keys=['df1','df2'])
the above code gives me below mentioned Dataframe. but how can I get the dataframe which is mentioned in the Expected output
actual_output_df =
df1 df2
empId emp_name counts emp_id emp_name counts
1 sam 0 1 sam 0
2 joe 0 2 joe 0
3 john 0 2 joe 1
NaN NaN NaN 3 john 0
通过传递不同的参数尝试了 pd.concat,但没有得到预期的结果。 我在 concat 中遇到的主要问题是,我无法将重复的行向下移动一行。
谁能帮我解决这个问题?提前致谢
【问题讨论】:
-
在上述问题中,'counts' 列对我来说不是必需的。如果需要,我可以放下它。
-
stackoverflow.com/questions/17095101/… 这与我正在寻找的非常相似,只是在此示例中没有重复的行,而我的示例中有重复的行。
标签: python pandas dataframe concatenation