python - 从下一列中删除 NaN 值和移位值
问题描述
我正在尝试从数据框中删除 NaN 值(不删除整个列或行)并将下一个值移动到前一列。例子:
CLIENT| ANIMAL_1 | ANIMAL_2 | ANIMAL_3| ANIMAL_4
ROW_1 1 | cow | frog | NaN | dog
ROW_2 2 | pig | NaN | cat | NaN
我的目标是:
CLIENT| ANIMAL_1 | ANIMAL_2 | ANIMAL_3| ANIMAL_4
ROW_1 1 | cow | frog | dog | NaN
ROW_2 2 | pig | cat | NaN | NaN
我试过的:
将每一行转换为列表并从每个列表中删除 NaN。但我似乎无法从列表中删除值:
x = df[df.CLIENT == 1].iloc[:,1:].values.tolist()
然后我得到:
[['cow', 'frog', nan, 'dog']]
删除我试过的'nan':
row_without_nan = [animal for animal in x if str(animal) != 'nan']
但它不会改变列表中的任何内容。我尝试将空值更改为另一个词并使用该词,但它也不起作用。
- 将每一行转换为数组。我尝试通过 using 转换为数组
np.array()
,但它没有用,因为空值变成了'nan'
,当我尝试使用时,np.isnan
我得到了这个:TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
有谁知道我的清单做错了什么,或者是否有更聪明/更快的方法来做到这一点?
解决方案
这是一种方法:
df_out = df.apply(lambda x: pd.Series(x.dropna().to_numpy()), axis=1)
df_out = df_out.set_axis(df.columns[:df_out.shape[1]], axis=1).reindex(df.columns, axis=1)
df_out
输出:
CLIENT ANIMAL_1 ANIMAL_2 ANIMAL_3 ANIMAL_4
ROW_1 1 cow frog dog NaN
ROW_2 2 pig cat NaN NaN
详细信息,在每一行上使用 dropna ,但是您需要转换为 numpy 数组以删除索引,然后将列标题分配给原始数据帧并沿列重新索引以获取数据帧末尾的所有空列。
推荐阅读
- javascript - 使用 javascript 格式化输入字段不适用于 form_widget
- swift - 多上下文麻烦。无法在 Core Data 中创建两个队列(主队列和私有队列)保存数据
- error-handling - 如何修复 MissingPermissions 错误不起作用 | 不和谐.py
- javascript - 将图像移回开始后如何?
- c# - 如何将平面 json 对象转换为强类型对象列表
- java - JavaFX在舞台上设置图标的问题
- python - Python:将数据从 .XML 输入到 .CSV 文件
- c# - 对于简单的提取/转换/加载任务,我应该使用哪种类型的项目?
- batch-file - 可以在 FOR 循环中对文件进行排序/排序吗?
- python - 如何让 Graphviz 垂直而不是水平显示图表?