【问题标题】:How to make np.where write True instead of 1.0?如何让 np.where 写 True 而不是 1.0?
【发布时间】:2020-12-11 20:46:27
【问题描述】:

我想用 True 和 NaN 值填充列

import numpy as np
import pandas as pd

my_list = [1,2,3,4,5]
df = pd.DataFrame({'col1' : [0,1,2,3,4,5,6,7,8,9,10]})
df['col2'] = np.where(df['col1'].isin(my_list), True, np.NaN)
print (df)

打印出来:

    col1  col2
0      0   NaN
1      1   1.0
2      2   1.0
3      3   1.0
4      4   1.0
5      5   1.0
6      6   NaN
7      7   NaN
8      8   NaN
9      9   NaN
10    10   NaN

但对我来说打印布尔值 True 而非浮点数 1.0 非常重要。此列与其他列交互。它们是布尔值,所以它也必须是布尔值。 我知道我可以用替换功能来改变它。但是我的 DataFrame 非常大。我不能浪费时间。有没有简单的选择?

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用Nullable Boolean data type:

    df['col2'] = pd.Series(np.where(df['col1'].isin(my_list), True, np.NaN), dtype='boolean')
    print (df)
        col1  col2
    0      0  <NA>
    1      1  True
    2      2  True
    3      3  True
    4      4  True
    5      5  True
    6      6  <NA>
    7      7  <NA>
    8      8  <NA>
    9      9  <NA>
    10    10  <NA>
    

    【讨论】:

    • 原谅我的无能!但是为什么 NaN 在这里看起来像 呢?
    • @IgorK。 - 不是incompetence。但是pandas开发者想区分NaNnullable NaN,所以用&lt;NA&gt;
    • 完美!你让我开心,节省了工作时间!!!!!!!
    【解决方案2】:

    此代码将解决您的问题。 np.where 将返回 true,因为 numpy 仅处理数字,而 True 表示数量为 1。这就是为什么它给你 1.0 而不是 True

    代码

    import numpy as np
    import pandas as pd
    
    my_list = [1,2,3,4,5]
    df = pd.DataFrame({'col1' : [0,1,2,3,4,5,6,7,8,9,10]})
    df['col2'] = df['col1'].apply(lambda x: True if x in my_list else np.NaN)
    print (df)
    

    结果

        col1  col2
    0      0   NaN
    1      1  True
    2      2  True
    3      3  True
    4      4  True
    5      5  True
    6      6   NaN
    7      7   NaN
    8      8   NaN
    9      9   NaN
    10    10   NaN
    

    【讨论】:

      【解决方案3】:

      你可以这样称呼

      df.col2 = df.col2.apply(lambda x: True if x==1.0 else x)
      

      【讨论】:

      • 这在性能方面不会像其他答案那样有效
      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多