Python 2.7 熊猫:根据现有值的分布填充要填充的NA值
我有一个pandas数据框,其中一列Python 2.7 熊猫:根据现有值的分布填充要填充的NA值,python-2.7,python-3.x,pandas,numpy,Python 2.7,Python 3.x,Pandas,Numpy,我有一个pandas数据框,其中一列sign-up有多个空值。注册列具有分类值,包括多个操作系统,如iOS、android、web等。 我想从现有的OS值中填充NA值,但NA值应按照OS值的现有分布进行填充 例如: 比如说,数据集的OS值计数分布如下: signup android web 14 ios web 16 mac 5 other 3 windows 6 Name: id, dtype: int64 b = d
sign-up
有多个空值。注册
列具有分类值,包括多个操作系统
,如iOS
、android
、web
等。
我想从现有的OS
值中填充NA
值,但NA值应按照OS
值的现有分布进行填充
例如:
比如说,数据集的OS值计数分布如下:
signup
android web 14
ios web 16
mac 5
other 3
windows 6
Name: id, dtype: int64
b = df.groupby('signup')['value'].first()[df['signup']]
b = pd.DataFrame(df.groupby('signup')['value'].first()[df['signup']],columns=['value']).reset_index()
b.rename({1:'value'})
我想根据上述不同OS值的分布填充NA值。我想做的原因是保持当前分布,因为填充模式
值可能会扭曲结果。
有人能帮你实现这一点吗。你可以使用类似Numpy的东西 从符合您描述的框架开始
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
使用piRSquared在评论中的提示更新了
计算当前的分布
s = df.signup.value_counts(normalize=True)
print(s)
windows 0.444444
mac 0.333333
other 0.222222
Name: signup, dtype: float64
我们将在要更新的NAN旁边使用布尔索引进行过滤。此外,我们通过传递索引(windows、mac、其他)使用随机选择,所需大小和每个注册的分布将用于概率(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
首先,我将此作为输入(因为我认为在您的问题中,您错误地命名了我的
值
列注册
:
signup value
0 android web 14.0
1 ios web 16.0
2 mac 5.0
3 other 3.0
4 windows 6.0
5 ios web NaN
6 mac NaN
7 windows NaN
知道了这一点,您的问题可以在一行中解决,如下所示:
signup
android web 14
ios web 16
mac 5
other 3
windows 6
Name: id, dtype: int64
b = df.groupby('signup')['value'].first()[df['signup']]
b = pd.DataFrame(df.groupby('signup')['value'].first()[df['signup']],columns=['value']).reset_index()
b.rename({1:'value'})
请不要认为b
属于pandas.Series类型
但是,如果希望输出为具有相同列名的数据帧,请按以下步骤进行:
signup
android web 14
ios web 16
mac 5
other 3
windows 6
Name: id, dtype: int64
b = df.groupby('signup')['value'].first()[df['signup']]
b = pd.DataFrame(df.groupby('signup')['value'].first()[df['signup']],columns=['value']).reset_index()
b.rename({1:'value'})
如果您打印(b)
,它将输出:
signup value
0 android web 14.0
1 ios web 16.0
2 mac 5.0
3 other 3.0
4 windows 6.0
5 ios web 16.0
6 mac 5.0
7 windows 6.0
- 查找空值
- 从非空值中采样空值的数量。确保设置
replace=True
- 将采样值分配给空位置
似乎我们没有以同样的方式理解这个问题,他的注册栏是带有NaN值的栏?谢谢Bob。这很有帮助。
df.signup.value\u counts(normalize=True)