【发布时间】: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 非常大。我不能浪费时间。有没有简单的选择?
【问题讨论】: