Pandas 与 fillna(0) 相反
Pandas opposite of fillna(0)
而df.fillna(0)
用0填充所有NA/NaN值,是否有函数用另一个值替换所有非-NA/NaN值, 比如 1?
如果我的 DataFrame 中的值是可变长度列表,那么:
df.replace()
要求列表长度相同
- 布尔索引像
df[len(df) > 0] = 1
抛出 ValueError: cannot insert True, already exists
pandas.get_dummies()
抛出 TypeError: unhashable type: 'list'
是否有更直接的解决方案?
我不知道有内置函数,但这行得通:
import pandas as pd
import numpy as np
df = pd.DataFrame(data={'a':[np.nan, 13, 32]})
>> a
0 NaN
1 13
2 32
df = df.applymap(lambda x: 1 if not np.isnan(x) else x)
>> a
0 NaN
1 1
2 1
您可以将 indexing/assignment 与 df[df.notnull()] = 1
一起使用。例如:
>>> df = pd.DataFrame([[np.nan, 2, 5], [2, 5, np.nan], [2, 5, np.nan]])
>>> df # example frame
0 1 2
0 NaN 2 5
1 2 5 NaN
2 2 5 NaN
>>> df[df.notnull()] = 1
>>> df
0 1 2
0 NaN 1 1
1 1 1 NaN
2 1 1 NaN
而df.fillna(0)
用0填充所有NA/NaN值,是否有函数用另一个值替换所有非-NA/NaN值, 比如 1?
如果我的 DataFrame 中的值是可变长度列表,那么:
df.replace()
要求列表长度相同- 布尔索引像
df[len(df) > 0] = 1
抛出ValueError: cannot insert True, already exists
pandas.get_dummies()
抛出TypeError: unhashable type: 'list'
是否有更直接的解决方案?
我不知道有内置函数,但这行得通:
import pandas as pd
import numpy as np
df = pd.DataFrame(data={'a':[np.nan, 13, 32]})
>> a
0 NaN
1 13
2 32
df = df.applymap(lambda x: 1 if not np.isnan(x) else x)
>> a
0 NaN
1 1
2 1
您可以将 indexing/assignment 与 df[df.notnull()] = 1
一起使用。例如:
>>> df = pd.DataFrame([[np.nan, 2, 5], [2, 5, np.nan], [2, 5, np.nan]])
>>> df # example frame
0 1 2
0 NaN 2 5
1 2 5 NaN
2 2 5 NaN
>>> df[df.notnull()] = 1
>>> df
0 1 2
0 NaN 1 1
1 1 1 NaN
2 1 1 NaN