简体   繁体   English

Python-遍历行和列

[英]Python - iterate over rows and columns

First of all, please pardon my skills. 首先,请原谅我的技能。 I am trying to get into Python, I learn just for fun, let's say, I don't use it professionally and I am quite bad, to be honest. 我试图进入Python,我只是为了好玩而学习,也就是说,我不是专业地使用它,老实说,我很糟糕。 Probably there will be basic errors on my question. 我的问题可能会有基本错误。

Anyway, I am trying to go over a dataframe's rows and columns. 无论如何,我试图遍历数据框的行和列。 I want to check if the values of the columns (except the first one) are NaNs. 我想检查列的值(第一个除外)是否为NaN。 If they are, then they should change to the value of the first one. 如果是,则应将其更改为第一个的值。

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 error I get is something like this: 我得到的错误是这样的:

the label [4.0] is not in the [columns] 标签[4.0]不在[列]中

I also had other errors with slightly different code like: 我也有其他错误,但代码略有不同,例如:

cannot do label indexing on class pandas.core.indexes.base.Index with these indexers class float 无法使用这些索引器类float对类pandas.core.indexes.base.Index进行标签索引

Could you give me a hand, please? 你能帮我一下吗?

Thanks in advance! 提前致谢!

Cheers. 干杯。

Where df is: df是:

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

Use transpose and fillna : 使用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. 由于fillna“ NotImplementedEerror” NotImplementedError:当前只能用dict / Series逐列df.fillna(value=df.A, axis=1)无法正常工作。 Therefore we use: 因此,我们使用:

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

Output: 输出:

     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

I don't know if there is a better way but this works fine: 我不知道是否有更好的方法,但是效果很好:

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

output: 输出:

   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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM