python - 用来自自身的样本填充列中的 NA
问题描述
简单的玩具数据框:
df = pd.DataFrame({'mycol':['foo','bar','hello','there',np.nan,np.nan,np.nan,'foo'],
'mycol2':'this is here to make it a DF'.split()})
print(df)
mycol mycol2
0 foo this
1 bar is
2 hello here
3 there to
4 NaN make
5 NaN it
6 NaN a
7 foo DF
我正在尝试用mycol
其自身的样本填充 NaN,例如,我希望将 NaN 替换为foo
、bar
等的样本hello
。
# fill NA values with n samples (n= number of NAs) from df['mycol']
df['mycol'].fillna(df['mycol'].sample(n=df.isna().sum(), random_state=1,replace=True).values)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
# fill NA values with n samples, n=1. Dropna from df['mycol'] before sampling:
df['mycol'] = df['mycol'].fillna(df['mycol'].dropna().sample(n=1, random_state=1,replace=True)).values
# nothing happens
预期输出:Nas 填充了来自以下的随机样本mycol
:
mycol mycol2
0 foo this
1 bar is
2 hello here
3 there to
4 foo make
5 foo it
6 hello a
7 foo DF
编辑答案: @Jezrael 下面的答案对其进行了排序,我的索引有问题。
df['mycol'] = (df['mycol']
.dropna()
.sample(n=len(df),replace=True)
.reset_index(drop=True))
解决方案
有趣的问题。
loc
对我来说,使用将值转换为 numpy 数组来避免数据对齐的工作集值:
a = df['mycol'].dropna().sample(n=df['mycol'].isna().sum(), random_state=1,replace=True)
print (a)
3 there
7 foo
0 foo
Name: mycol, dtype: object
#pandas 0.24+
df.loc[df['mycol'].isna(), 'mycol'] = a.to_numpy()
#pandas below
#df.loc[df['mycol'].isna(), 'mycol'] = a.values
print (df)
mycol mycol2
0 foo this
1 bar is
2 hello here
3 there to
4 there make
5 foo it
6 foo a
7 foo DF
如果系列和索引的长度与原始长度相同,您的解决方案应该可以工作DataFrame
:
s = df['mycol'].dropna().sample(n=len(df), random_state=1,replace=True)
s.index = df.index
print (s)
0 there
1 foo
2 foo
3 bar
4 there
5 foo
6 foo
7 bar
Name: mycol, dtype: object
df['mycol'] = df['mycol'].fillna(s)
print (df)
# mycol mycol2
0 foo this
1 bar is
2 hello here
3 there to
4 there make
5 foo it
6 foo a
7 foo DF
推荐阅读
- c++ - 计算已排序文本文件 C++ 中的重复次数
- azure - 如何在 Azure 函数输出绑定中禁用 Blob 存在检查
- excel - 使用宏保存 Excel 工作簿时日期反转
- python - 如果列表目录提到 __count__ 和 __len___ 为什么使用这两个运算符的语法不同?
- javascript - html5画布上两条贝塞尔曲线下的填充区域
- xcode - SwiftUI 隐藏状态栏
- python - RelatedObjectDoesNotExist at /register/ 用户没有 schoolprofile
- c++ - 在 C++ 中使用带有 boost::mpl::find_if 的自定义一元谓词
- php - 使用 Sendgrid API 从本地主机发送邮件 - Php 和 Curl 集成
- swift - 如何从磁盘加载此图像数据并将其呈现在我的 SwiftUI 列表中?