[英]pandas : appending columns to df that is prat of another df
I have 2 pandas DataFrames:我有 2 个 pandas 数据帧:
df1: df1:
c1 ![]() |
c2 ![]() |
x ![]() |
---|---|---|
1 ![]() |
1 ![]() |
1 ![]() |
2 ![]() |
1 ![]() |
4 ![]() |
1 ![]() |
2 ![]() |
1 ![]() |
2 ![]() |
2 ![]() |
4 ![]() |
and df2:和 df2:
c1 ![]() |
c2 ![]() |
c3 ![]() |
---|---|---|
1 ![]() |
1 ![]() |
1 ![]() |
1 ![]() |
2 ![]() |
1 ![]() |
2 ![]() |
2 ![]() |
2 ![]() |
and I want to append the x
row to df2
like:我想 append
x
行到df2
像:
c1 ![]() |
c2 ![]() |
c3 ![]() |
x ![]() |
---|---|---|---|
1 ![]() |
1 ![]() |
1 ![]() |
1 ![]() |
1 ![]() |
2 ![]() |
1 ![]() |
1 ![]() |
2 ![]() |
2 ![]() |
2 ![]() |
4 ![]() |
I tried to use join
, but because I don't have a unique index, it didn't work:我尝试使用
join
,但因为我没有唯一索引,所以它不起作用:
df1.set_index(['c1', 'c2'], inplace=True)
df2.set_index(['c1', 'c2'], inplace=True,drop=False)
df2=df2.join(df1)
df2: df2:
c1 ![]() |
c2 ![]() |
c3 ![]() |
x ![]() |
---|---|---|---|
1 ![]() |
1 ![]() |
1 ![]() |
Nan![]() |
1 ![]() |
2 ![]() |
1 ![]() |
Nan![]() |
2 ![]() |
2 ![]() |
2 ![]() |
Nan![]() |
Perhaps the simplest way to do what your question asks is this:也许做你的问题所问的最简单的方法是这样的:
df2 = pd.merge(df2, df1, on=['c1', 'c2'])
We have done an 'inner' join (the default for pandas.merge()) on columns c1
and c2
of dataframes df1 and df2.我们在数据帧 df1 和 df2 的
c1
和c2
列上进行了“内部”连接(pandas.merge() 的默认值)。
Alternatively, this is a way to get the specified result using DataFrame.join() in an approach similar to the one you tried according to your question:或者,这是一种使用 DataFrame.join() 获得指定结果的方法,其方法类似于您根据问题尝试过的方法:
df2 = df2.set_index(['c1', 'c2']).join(df1.set_index(['c1', 'c2'])).reset_index()
Result:结果:
c1 c2 c3 x
0 1 1 1 1
1 1 2 1 1
2 2 2 2 4
Note that inplace
has been removed as its use is generally discouraged , and we now go ahead and allow c1 and c2 columns of df2 to be dropped by set_index() and use reset_index() later to restore them.请注意,
inplace
已被删除,因为通常不鼓励使用它,我们现在提前 go 并允许 df2 的 c1 和 c2 列被 set_index() 删除,稍后使用 reset_index() 来恢复它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.