我有一个大数据框,这是数据框的示例部分。 想要交换马斯喀特和上海的值(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
关于python - 如何交换 Dataframe 中的特定列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502038/