从下一列中删除NaN值和shift值

2024-06-01 07:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从数据帧中删除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

我所尝试的:

  1. 将每一行转换为列表,并从每一行中删除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']

但它不会改变列表中的任何内容。我试着把空值改成另一个词,然后用那个词,但也没用

  1. 将每行转换为数组。我尝试使用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''

有没有人知道我的列表有什么地方做错了,或者有没有更聪明/更快的方法


Tags: theclientdf列表fornancatrow
3条回答

这里有一个方法:

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数组以删除索引,然后将列标题分配给原始数据帧,并沿列重新索引以拾取数据帧末尾的所有空列

下面是另一种方法:

def drop_nan(r):
    r = list(r)
    r = [x for x in r if isinstance(x, str) or not np.isnan(x)]
    return r

res = pd.DataFrame.from_records(df.apply(drop_nan, axis=1))
res.columns = df.columns[:len(res.columns)]

结果是:

   CLIENT ANIMAL_1 ANIMAL_2 ANIMAL_3
0       1      cow     frog      dog
1       2      pig      cat     None

您的方法可能还可以,但您可能遇到的问题是,在从数据帧获得数组或列表后,您得到了一个嵌套列表,即['cow','frog',nan',dog']]。请注意双括号。你需要去掉一对括号。尝试类似于y=x[0]的方法。然后再次运行nan删除代码

相关问题 更多 >