I know that you can use pandas.DataFrame.fillna
to replace all null values with a Series, but is there an easy way to replace all non-null values with a Series?
Alternatively, I have seen df.loc[~df.isnull()]
for replacing all null values with a single value, but again - is there a way to pass in a Series?
Edit: For example, say I have a DataFrame df
with a column called code
which contains some null values and some non-null values. Then say I have a Series called new_code
which contains only non-null values. I want to replace all of the non-null values in df['code']
with the values of new_code
(where the number of non-null values is equal to the length of new_code
).
You can do it as below.
Since you have not provided a df, I am using my own df (input & output shown). 'f' is the series that has been created.
a = df.loc[~df['Age'].isnull()]
b = df.loc[~df['Age'].isnull()].index
f= pd.Series([i for i in range(1,12)], index=b)
df.loc[~df['Age'].isnull(),['Age']]=f
Input
Country Age
0 USA NaN
1 EU 15.0
2 China 35.0
3 USA 45.0
4 EU NaN
5 China NaN
6 USA 28.0
7 EU 26.0
8 China 78.0
9 USA 65.0
10 EU 53.0
11 China 66.0
12 USA 32.0
13 EU NaN
14 China 14.0
f
1 1
2 2
3 3
6 4
7 5
8 6
9 7
10 8
11 9
12 10
14 11
Output
Country Age
0 USA NaN
1 EU 1.0
2 China 2.0
3 USA 3.0
4 EU NaN
5 China NaN
6 USA 4.0
7 EU 5.0
8 China 6.0
9 USA 7.0
10 EU 8.0
11 China 9.0
12 USA 10.0
13 EU NaN
14 China 11.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.