简体   繁体   English

熊猫数据框中的NaN值不变

[英]NaN values in pandas dataframe doesnt change

I have got a pandas dataframe which looks like this. 我有一个看起来像这样的熊猫数据框。

import pandas as pd
import math

inp = [{'c1':-5, 'c2':-2, 'c3':-3,'c4:360}, {'c1'1:, 'c2':-3, 'c3':4,'c4:550}, {'c1':NaN, 'c2':NaN, 'c3':NaN,'c4:NaN}]
df = pd.DataFrame(inp)

Output: 输出:

   c1  c2  c3  c4
0  -5  -2  -3  360
1   1  -3  4   550
2  NaN NaN NaN NaN

I want to itterate through the rows and change those who got an NaN value in c4. 我想遍历行并更改在c4中获得NaN值的那些行。 and then change the value in all of the cells which have got this. 然后更改所有已获得此值的单元格中的值。

for index, row in df.iterrows():
    if math.isnan(row["c4"]) == True:
    row["c1"] = float(0)
    row["c2"] = float(df["c1"][0]) + float(df["c2"][0])
    row["c3"] = row["c2"] - row["c1"]
    row["c4"] = float(2880)

For the first column it should just be 0. 对于第一列,它应该只是0。

For the second column it should be the first rows values in c1 and c2 added together. 对于第二列,应该将c1和c2中的第一行值加在一起。

For the third column should be the first columns minus the second column. 对于第三列,应该是第一列减去第二列。

And the last column should just be 2880. 最后一列应该是2880。

When i run the code above i do not get an error but the dataframe doesnt change at all. 当我运行上面的代码时,我没有收到错误,但数据框完全没有变化。 Can any1 tell me why or help me writing some code that does this? 任何人都可以告诉我为什么还是帮我编写一些这样做的代码?

Appreciate it! 赞赏!

You can avoid looping by using regular indexing: 您可以通过使用常规索引来避免循环:

idx = df.c4.isnull()
df.loc[idx,'c1'] = 0
df.loc[idx,'c2'] = df.iloc[0,0] + df.iloc[0,1]
df.loc[idx,'c3'] = df.loc[idx,'c2'] - df.loc[idx,'c1']
df.loc[idx,'c4'] = 2880.

Output: 输出:

 c1   c2   c3      c4
0 -5.0 -2.0 -3.0   360.0
1  1.0  3.0  4.0   550.0
2  0.0 -7.0 -7.0  2880.0

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

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