【发布时间】:2020-10-19 22:23:42
【问题描述】:
我正在尝试从数据框中删除 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']
但它不会改变列表中的任何内容。我尝试将空值更改为另一个词并使用该词,但它也不起作用。
- 将每一行转换为数组。我尝试使用
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''
有谁知道我的清单做错了什么,或者是否有更智能/更快的方法?
【问题讨论】:
标签: python pandas list dataframe nan