[英]Pandas opposite of fillna(0)
Whereas df.fillna(0)
fills all NA/NaN values with 0, is there a function to replace all non -NA/NaN values with another value, such as 1? df.fillna(0)
用df.fillna(0)
填充所有NA / NaN值,是否有一个函数用另一个值(例如1)替换所有非 -NA / NaN值?
If the values in my DataFrame are variable-length lists then: 如果我的DataFrame中的值是可变长度列表,则:
df.replace()
requires that the lists are the same length df.replace()
要求列表长度相同 df[len(df) > 0] = 1
throws ValueError: cannot insert True, already exists
df[len(df) > 0] = 1
抛出ValueError: cannot insert True, already exists
pandas.get_dummies()
throws TypeError: unhashable type: 'list'
pandas.get_dummies()
引发TypeError: unhashable type: 'list'
Is there a more straightforward solution? 有没有更直接的解决方案?
You could use indexing/assignment with df[df.notnull()] = 1
. 您可以使用
df[df.notnull()] = 1
索引/分配。 For instance: 例如:
>>> 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
I don't know of a built-in function, but this works: 我不知道内置函数,但这可行:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.