首页 > 解决方案 > 如何交换 Dataframe 中的特定列值?

问题描述

我有一个大数据框,这是数据框的示例部分。想交换马斯喀特和上海的价值观。

 df =
 City   Score

 Istanbul   6.0749
 2.23607    Muscat
 Prague     4.38576
 1.85958    Shanghai
 Istanbul   6.0749
 Singapore  5.17054

输出:

 df = 
 City   Score

 Istanbul   6.0749
 Muscat     2.23607     
 Prague     4.38576
 Shanghai   1.85958     
 Istanbul   6.0749
 Singapore  5.17054

我很困惑,在遍历数据框后如何应用条件,还有其他选择吗?

标签: pythonpandasdataframe

解决方案


用于布尔掩码to_numericnotna然后交换loc

m = pd.to_numeric(df['City'], errors='coerce').notna()
#oldier versions of pandas
#m = pd.to_numeric(df['City'], errors='coerce').notnull()
df.loc[m,['City','Score']] = df.loc[m,['Score','City']].values

print (df)
        City    Score
0   Istanbul   6.0749
1     Muscat  2.23607
2     Prague  4.38576
3   Shanghai  1.85958
4   Istanbul   6.0749
5  Singapore  5.17054

推荐阅读