use*_*236 2 numpy python-2.7 python-3.x pandas
我有一个pandas数据框,其中一列sign up
有多个空值.所述sign up
柱具有包括多个分类值OS
如iOS
,android
,web
等.我想以填充NA
从现有值OS
的值,但该值NA应填充按照现有分配OS
的值.
示例:假设数据集具有OS值计数分布,如下所示:
signup
android web 14
ios web 16
mac 5
other 3
windows 6
Name: id, dtype: int64
Run Code Online (Sandbox Code Playgroud)
我想根据不同OS值的上述分布来填充NA值.我想要做的是保持当前的分布,因为填充Mode
价值可能会扭曲结果.有人可以帮助如何实现这一目标.
你可以使用像Numpy的random.choice这样的东西
从符合您描述的框架开始
import numpy as np
import pandas as pd
print(df)
id signup
0 1 mac
1 2 mac
2 3 mac
3 4 other
4 5 other
5 6 windows
6 7 windows
7 8 windows
8 9 windows
9 10 NaN
10 11 NaN
11 12 NaN
12 13 NaN
13 14 NaN
Run Code Online (Sandbox Code Playgroud)
使用piRSquared的提示在评论中更新了当前的分布
s = df.signup.value_counts(normalize=True)
print(s)
windows 0.444444
mac 0.333333
other 0.222222
Name: signup, dtype: float64
Run Code Online (Sandbox Code Playgroud)
我们将在我们想要更新的nans过滤器旁边使用布尔索引.此外,这是我们通过传递索引(windows,mac,other)来使用随机选择的地方,所需的大小和每个注册的分布将用于概率(p)参数.
missing = df['signup'].isnull()
df.loc[missing,'signup'] = np.random.choice(s.index, size=len(df[missing]),p=s.values)
print(df)
id signup
0 1 mac
1 2 mac
2 3 mac
3 4 other
4 5 other
5 6 windows
6 7 windows
7 8 windows
8 9 windows
9 10 windows
10 11 windows
11 12 mac
12 13 windows
13 14 other
Run Code Online (Sandbox Code Playgroud)