Python - 遍历行和列

Python - iterate over rows and columns

首先请大家见谅我的技能。我正在努力进入Python,我只是为了好玩而学习,比方说,我不专业使用它而且我很糟糕,说实话。我的问题可能会有基本错误。

无论如何,我正在尝试检查数据框的行和列。我想检查列的值(第一列除外)是否为 NaN。如果是,则应更改为第一个的值。

import math

for index, row in rawdata3.iterrows():
    test = row[0]
    for column in row:
        if math.isnan(row.loc[column]) == True:
            row.loc[column] = test

我得到的错误是这样的:

the label [4.0] is not in the [columns]

我还有其他错误,代码略有不同,例如:

cannot do label indexing on class pandas.core.indexes.base.Index with these indexers class float

你能帮我一下吗?

提前致谢!

干杯。

其中 df 是:

   A    B    C
0  5  NaN  2.0
1  6  5.0  NaN
2  9  NaN  NaN
3  2  4.0  6.0

使用transposefillna:

Due to fillna "NotImplementedEerror" NotImplementedError: Currently only can fill with dict/Series column by column df.fillna(value=df.A, axis=1) will not work. Therefore we use:

df.T.fillna(df.A).T

输出:

     A    B    C
0  5.0  5.0  2.0
1  6.0  5.0  6.0
2  9.0  9.0  9.0
3  2.0  4.0  6.0

我不知道是否有更好的方法,但这很好用:

for i in df.columns:
    df.loc[df[i].isnull(), i] = df.loc[df[i].isnull(), 'A']

输出:

   A    B    C
0  5  5.0  2.0
1  6  5.0  6.0
2  9  9.0  9.0
3  2  4.0  6.0