【问题标题】:How to replace the values of a column to other columns only in NaN values?如何仅在 NaN 值中将列的值替换为其他列?
【发布时间】:2022-01-14 17:09:35
【问题描述】:

如何仅在 NaN 值中用另一个 column ["country"] 填充 column ["state"] 的值?

就像在这个 Pandas DataFrame 中一样:

         state   country  sum
0          NaN     China    1
1        Assam     India    2
2        Odisa     India    3
3        Bihar     India    4
4          NaN     India    5
5          NaN  Srilanka    6
6          NaN   Malaysia   7
7          NaN    Bhutan    8
8   California        US    9
9        Texas        US   10
10     Newyork        US   11
11         NaN        US   12
12         NaN    Canada   13

我应该执行什么代码来仅在 NaN 值中使用国家列填充州列,如下所示:

         state   country  sum
0        China     China    1
1        Assam     India    2
2        Odisa     India    3
3        Bihar     India    4
4        India     India    5
5     Srilanka  Srilanka    6
6     Malaysia  Malaysia    7
7       Bhutan    Bhutan    8
8   California        US    9
9        Texas        US   10
10     Newyork        US   11
11          US        US   12
12      Canada    Canada   13

我可以使用这个代码:

df.loc[df['state'].isnull(), 'state'] = df[df['state'].isnull()]['country'].replace(df['country'])

但是在一个包含 300K 行的非常大的数据集中,它计算 5-6 分钟并且每次都崩溃。因为它一次替换一个值。 Like this 任何人都可以帮我提供有效的代码吗? 请!

【问题讨论】:

    标签: python pandas database dataframe replace


    【解决方案1】:

    也许使用 fillna 而不检查 isnull() 和 replace():

    df['state'].fillna(df['country'], inplace=True)
    print(df)
    

    输出

             state   country  sum
    0        China     China    1
    1        Assam     India    2
    2        Odisa     India    3
    3        Bihar     India    4
    4        India     India    5
    5     Srilanka  Srilanka    6
    6     Malaysia  Malaysia    7
    7       Bhutan    Bhutan    8
    8   California        US    9
    9        Texas        US   10
    10     Newyork        US   11
    11          US        US   12
    12      Canada    Canada   13
    

    【讨论】:

    • 谢谢你,我当时明白了,但感谢你的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2019-10-11
    相关资源
    最近更新 更多