I am working with this Pandas DataFrame in Python.
JavaScript
x
20
20
1
File heat Farheit Temp_Rating
2
1 YesQ 75 N/A
3
1 NoR 115 N/A
4
1 YesA 63 N/A
5
1 NoT 83 41
6
1 NoY 100 80
7
1 YesZ 56 12
8
2 YesQ 111 N/A
9
2 NoR 60 N/A
10
2 YesA 19 N/A
11
2 NoT 106 77
12
2 NoY 45 21
13
2 YesZ 40 54
14
3 YesQ 84 N/A
15
3 NoR 67 N/A
16
3 YesA 94 N/A
17
3 NoT 68 39
18
3 NoY 63 46
19
3 YesZ 34 81
20
I need to replace all NaNs in the Temp_Rating
column with the value from the Farheit
column.
This is what I need:
JavaScript
1
20
20
1
File heat Temp_Rating
2
1 YesQ 75
3
1 NoR 115
4
1 YesA 63
5
1 YesQ 41
6
1 NoR 80
7
1 YesA 12
8
2 YesQ 111
9
2 NoR 60
10
2 YesA 19
11
2 NoT 77
12
2 NoY 21
13
2 YesZ 54
14
3 YesQ 84
15
3 NoR 67
16
3 YesA 94
17
3 NoT 39
18
3 NoY 46
19
3 YesZ 81
20
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 NaN
s and replace them with the value in the same row of the Farheit
column?
Advertisement
Answer
Assuming your DataFrame is in df
:
JavaScript
1
4
1
df.Temp_Rating.fillna(df.Farheit, inplace=True)
2
del df['Farheit']
3
df.columns = 'File heat Observations'.split()
4
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
: