用不同的数字在数据框中填充 NaN
Fill NaNs in dataframe with different numbers
我有一个 df:
df = pd.DataFrame({'Col1': [np.NaN, 1, 2], 'Col2': [7, 9, np.NaN], 'Col3': [np.NaN, np.NaN, 5]})
如何用 df
中不存在的随机唯一数字替换 df
中的每个 NaN,例如:
df = pd.DataFrame({'Col1': [8, 1, 2], 'Col2': [7, 9, 11], 'Col3': [30, 33, 5]})
非常感谢。
一种方法是用相同大小的随机数 df 进行掩码:
import random
total_size = df.shape[0]*df.shape[1]
rands = [x for x in random.sample(range(total_size*10), total_size*2) if x not in df.values][:total_size]
rands_mat = np.array(rands).reshape((df.shape))
df.mask(pd.isnull(df), rands_mat)
Col1
Col2
Col3
0
4
7
23
1
1
9
19
2
2
71
5
我有一个 df:
df = pd.DataFrame({'Col1': [np.NaN, 1, 2], 'Col2': [7, 9, np.NaN], 'Col3': [np.NaN, np.NaN, 5]})
如何用 df
中不存在的随机唯一数字替换 df
中的每个 NaN,例如:
df = pd.DataFrame({'Col1': [8, 1, 2], 'Col2': [7, 9, 11], 'Col3': [30, 33, 5]})
非常感谢。
一种方法是用相同大小的随机数 df 进行掩码:
import random
total_size = df.shape[0]*df.shape[1]
rands = [x for x in random.sample(range(total_size*10), total_size*2) if x not in df.values][:total_size]
rands_mat = np.array(rands).reshape((df.shape))
df.mask(pd.isnull(df), rands_mat)
Col1 | Col2 | Col3 | |
---|---|---|---|
0 | 4 | 7 | 23 |
1 | 1 | 9 | 19 |
2 | 2 | 71 | 5 |