【问题标题】:Combine dataframes of different sizes without NAN's [duplicate]在没有 NAN 的情况下组合不同大小的数据帧 [重复]
【发布时间】:2017-11-12 03:57:01
【问题描述】:

我有 2 个数据框,我想通过以下方式组合: df1:

I   A           B           C
0   0.719391    0.091693    one
1   0.951499    0.83716     one
2   0.975212    0.224855    one
3   0.80762     0.031284    three
4   0.63319     0.342889    one
5   0.075102    0.899291    two
6   0.502843    0.773424    two
7   0.032285    0.242476    one
8   0.794938    0.607745    one

df2:

I   Y   C
0   1   one
1   2   two
2   3   three

结果是: df_comb:

I   A           B           C       Y
0   0.719391    0.091693    one     1
1   0.951499    0.83716     one     1
2   0.975212    0.224855    one     1
3   0.80762     0.031284    three   3
4   0.63319     0.342889    one     1
5   0.075102    0.899291    two     2
6   0.502843    0.773424    two     2
7   0.032285    0.242476    one     1
8   0.794938    0.607745    one     1

因此,df_comb 的 Y 列中 C 列的值与 df2 的 C 列中的值匹配的每一行都应该在其 Y 列中具有 df2 中 Y 列的对应值。

我尝试了一些加入和合并,但没有成功。 有谁知道如何在不使用 for 循环的情况下做到这一点?

谢谢

【问题讨论】:

  • 我们可以看看您的合并尝试失败吗?因为这绝对看起来像是一个合并问题。
  • @ayhan 你能找到骗子吗?
  • @cᴏʟᴅsᴘᴇᴇᴅ jezrael 击败了我。 :)
  • @ayhan 令人惊喜!

标签: python pandas join merge


【解决方案1】:

选项 1
df.map

df['Y']=df.C.map(df2.set_index('C')['Y'])
df
Out[164]: 
   I         A         B      C  Y
0  0  0.719391  0.091693    one  1
1  1  0.951499  0.837160    one  1
2  2  0.975212  0.224855    one  1
3  3  0.807620  0.031284  three  3
4  4  0.633190  0.342889    one  1
5  5  0.075102  0.899291    two  2
6  6  0.502843  0.773424    two  2
7  7  0.032285  0.242476    one  1
8  8  0.794938  0.607745    one  1

选项 2
df.merge

df.merge(df2, on='C', how='left')

          A         B      C  Y
0  0.719391  0.091693    one  1
1  0.951499  0.837160    one  1
2  0.975212  0.224855    one  1
3  0.633190  0.342889    one  1
4  0.032285  0.242476    one  1
5  0.794938  0.607745    one  1
6  0.807620  0.031284  three  3
7  0.075102  0.899291    two  2
8  0.502843  0.773424    two  2

选项 3
df.replace

df.C.replace(df2.set_index('C').Y)

I
0    1
1    1
2    1
3    3
4    1
5    2
6    2
7    1
8    1
Name: C, dtype: int64

【讨论】:

  • 合并了我们的答案,希望没问题。
  • @cᴏʟᴅsᴘᴇᴇᴅ 在这里替换:-)
  • 伙计们,这是一个非常好的答案+1 :)
  • 嗯,如果欺骗回答最好是删除它?或不?各位,你们怎么看?
  • community wiki ?
猜你喜欢
  • 2019-10-14
  • 2020-08-23
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 1970-01-01
相关资源
最近更新 更多