简体   繁体   English

如何用另一列的值填充 Pandas 列的 NaN 值

[英]how to fill NaN values of Pandas column with values from another column

I have a column with missing values after a certain number of rows, and another column with missing values up to that point.我有一列在一定数量的行之后有缺失值,另一列在该点之前有缺失值。 How can I join the two columns so that I have one column with all the values?如何连接两列,以便有一列包含所有值?

Columns as is:列原样:

         COL 1      COL 2 
0            A        NaN
1            B        NaN  
2            C        NaN 
3          NaN          D   
4          NaN          E
5          NaN          F

Expected output:预期输出:

         COL 1      
0            A             
1            B             
2            C            
3            D           
4            E          
5            F           

Use Series.fillna or Series.combine_first :使用Series.fillnaSeries.combine_first

df['COL 1'] = df['COL 1'].fillna(df['COL 2'])

df['COL 1'] = df['COL 1'].combine_first(df['COL 2'])

If want also remove second column add DataFrame.pop :如果还想删除第二列添加DataFrame.pop

df['COL 1'] = df['COL 1'].fillna(df.pop('COL 2'))
#df['COL 1'] = df['COL 1'].combine_first(df.pop('COL 2'))

You have to use fillna() with 'COL2' values on 'COL1' and then drop 'COL2'您必须在“COL1”上使用带有“COL2”值的 fillna(),然后删除“COL2”

df['COL1'] = df['COL1'].fillna(df['COL2'])
df = df.drop(columns='COL2')

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

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