如果一个列存在并且另一个列为NaN/Null,则Pandas将值从一个列复制到另一个列


import pandas as pd
import io
output = """
name    weight   performance_l    performance_r
Arash   62.2                   100       
Bash    91.2       90           79       
Kim     88.2       85           85      
Dim     92.1       90           95
Ghst    63.2       60           65      
"""
df = pd.read_table(io.StringIO(output), delim_whitespace=True)

以上是我的数据框架,我希望使用perfomance_lperformance_r。如果performance_lperformance_r中有一个为Null…将存在的值复制到其他列,否则忽略所有数据框。

预期输出:

output = """
name    weight   performance_l    performance_r
Arash   62.2       100          100       
Bash    91.2       90           79       
Kim     88.2       85           85      
Dim     92.1       90           95
Ghst    63.2       60           65      
"""
df = pd.read_table(io.StringIO(output), delim_whitespace=True)

如何实现这一点?

使用fillna:

df['performance_l'] = df['performance_l'].fillna(df['performance_r'])
df['performance_r'] = df['performance_r'].fillna(df['performance_l'])

相关内容

最新更新