Skip to main content
 首页 » 编程设计

python之如何交换 Dataframe 中的特定列值

2025年05月04日23exmyth

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

 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 

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

请您参考如下方法:

使用to_numeric与 notna对于 bool 掩码,然后交换 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