Python Pandas将一列中的NaN替换为第二列的相应行的值 [英] Python Pandas replace NaN in one column with value from corresponding row of second column

查看:3717
本文介绍了Python Pandas将一列中的NaN替换为第二列的相应行的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 文件加热Farheit Temp_Rating 
1是Q 75 N / A
1 NoR 115 N / A
1是A 63 N / A
1 NoT 83 41
1 NoY 100 80
1 YesZ 56 12
2 YesQ 111 N / A
2 NoR 60 N / A
2是A 19 N / A
2 NoT 106 77
2 NoY 45 21
2 YesZ 40 54
3 YesQ 84 N / A
3 NoR 67 N / A
3是A 94 N / A
3 NoT 68 39
3 NoY 63 46
3 YesZ 34 81

我需要替换 Temp_Rating 列,其值来自 Farheit 列。



这是我需要的: p>

 文件热观察
1是Q 75
1 NoR 115
1是A 63
1是Q 41
1 NoR 80
1是A 12
2是Q 111
2 NoR 60
2是A 19
2 NoT 77
2 NoY 21
2 YesZ 54
3是Q 84
3 NoR 67
3是A 94
3 NoT 39
3 NoY 46
3 YesZ 81

如果我做一个布尔选择,我一次只能选出这些列之一。问题是如果我尝试加入他们,我不能这样做,同时保持正确的顺序。



如何找到 Temp_Rating 行与 NaN s,并将它们替换为 Farheit 列?

解决方案

假设您的DataFrame位于 df / p>

  df.Temp_Rating.fillna(df.Farheit,inplace = True)
del df ['Farheit']
df.columns ='文件热观察'.split()

首先替换任何 NaN 值,相应的值为 df.Farheit 。删除'Farheit'列。然后重命名列。以下是生成的 DataFrame




I am working with this Pandas DataFrame in Python 2.7.

File    heat    Farheit Temp_Rating
   1    YesQ    75      N/A
   1    NoR     115     N/A
   1    YesA    63      N/A
   1    NoT     83      41
   1    NoY     100     80
   1    YesZ    56      12
   2    YesQ    111     N/A
   2    NoR     60      N/A
   2    YesA    19      N/A
   2    NoT     106     77
   2    NoY     45      21
   2    YesZ    40      54
   3    YesQ    84      N/A
   3    NoR     67      N/A
   3    YesA    94      N/A
   3    NoT     68      39
   3    NoY     63      46
   3    YesZ    34      81

I need to replace all NaNs in the Temp_Rating column with the value from the Farheit column.

This is what I need:

File        heat    Observation
   1        YesQ    75
   1        NoR     115
   1        YesA    63
   1        YesQ    41
   1        NoR     80
   1        YesA    12
   2        YesQ    111
   2        NoR     60
   2        YesA    19
   2        NoT     77
   2        NoY     21
   2        YesZ    54
   3        YesQ    84
   3        NoR     67
   3        YesA    94
   3        NoT     39
   3        NoY     46
   3        YesZ    81

If I do a Boolean selection, I can pick out only one of these columns at a time. The problem is if I then try to join them, I am not able to do this while preserving the correct order.

How can I only find Temp_Rating rows with the NaNs and replace them with the value in the same row of the Farheit column?

解决方案

Assuming your DataFrame is in df:

df.Temp_Rating.fillna(df.Farheit, inplace=True)
del df['Farheit']
df.columns = 'File heat Observations'.split()

First replace any NaN values with the corresponding value of df.Farheit. Delete the 'Farheit' column. Then rename the columns. Here's the resulting DataFrame:

这篇关于Python Pandas将一列中的NaN替换为第二列的相应行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆