【问题标题】:How to replace subset of pandas dataframe with on other series如何用其他系列替换熊猫数据框的子集
【发布时间】:2017-02-12 12:41:00
【问题描述】:

我认为这是一个微不足道的问题,但我就是无法让它发挥作用。

d = {   'one': pd.Series([1,2,3,4], index=['a', 'b', 'c', 'd']),
            'two': pd.Series([np.nan,6,np.nan,8], index=['a', 'b', 'c', 'd']),
            'three': pd.Series([10,20,30,np.nan], index = ['a', 'b', 'c', 'd'])}         
   ​    
df = pd.DataFrame(d)
df

    one     three   two
a   1       10.0    NaN
b   2       20.0    6.0
c   3       30.0    NaN
d   4       NaN     8.0

我的系列:

​fill = pd.Series([30,60])

我想替换一个特定的列,让它成为“两个”。使用我的名为 fill 的系列,“二”列满足一个条件:是 Nan。你能帮我解决这个问题吗? 我想要的结果:

df

    one     three   two
a   1       10.0    30
b   2       20.0    6.0
c   3       30.0    60
d   4       NaN     8.0

【问题讨论】:

    标签: python pandas data-analysis missing-data


    【解决方案1】:

    我认为你需要 locisnull 来替换 numpy arrayfill 创建的 Series.values:

    df.loc[df.two.isnull(), 'two'] = fill.values
    print (df)
       one  three   two
    a    1   10.0  30.0
    b    2   20.0   6.0
    c    3   30.0  60.0
    d    4    NaN   8.0
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多