【问题标题】:How to replace whole cell in pandas, with values from other dataframe and rest to be set as 1?如何用其他数据框的值替换熊猫中的整个单元格并将其余部分设置为1?
【发布时间】:2020-09-14 22:00:25
【问题描述】:

我有两个 DataFrame。 df1:

A    |    B    |    C
-----|---------|---------|
25zx | b(50gh) |         |
50tr | a(70lc) | c(50gh) |

df2:

  A  |  B
-----|-----
  b  | 1.2
  a  | 3.5
  c  |  6

我想替换 df1 中的值。我要比较的行是 df2['A'],但我想放入 df1 的值是 df['B'] 行的值。请注意,我的目标是替换整个单元格的新值,并将没有任何内容可替换的单元格设置为 1。

所以决赛桌看起来像:

df3:

A    |    B    |    C
-----|---------|---------|
  1  |   1.2   |    1    |
  1  |   3.5   |    6    |

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用regexreplace 然后apply to_numeric 后跟fillna

    df3 = df1.replace(df2.set_index('A').B,regex=True)
    df3 = df3.apply(pd.to_numeric,errors='coerce').fillna(1)
    df3
    Out[123]: 
         A    B    C
    0  1.0  1.2  1.0
    1  1.0  3.5  6.0
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 2016-04-22
      • 2015-02-15
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多