如何交换Dataframe中的特定列值?

2024-09-28 21:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大数据帧这是数据帧的样本部分。 想交换马斯喀特和上海的价值。在

 df =
 City   Score

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

输出:

^{pr2}$

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


Tags: 数据citydataframedf条件score样本价值
2条回答

您可以使用:

In [39]: mask = pd.to_numeric(df.Score, errors='coerce').isna()

In [40]: s = df.Score.copy()

In [41]: df.Score[mask] = df.City

In [42]: df.City[mask] = s

In [43]: df
Out[43]: 
        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

使用^{}^{}作为布尔掩码,然后按^{}交换:

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

相关问题 更多 >