python - 如何交换 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
我很困惑,在遍历数据框后如何应用条件,还有其他选择吗?
解决方案
用于布尔掩码to_numeric
,notna
然后交换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
推荐阅读
- clearcase - 清除返回的文本文件
- outlook-addin - Outlook 插件页面无法在 F12Choosers 中显示
- php - 如何组织注册表以正确处理这4种情况?
- javascript - 在Javascript中映射并从数组中删除逗号
- reactjs - React JS/Firebase/React 引导表 - 为什么在删除最后一个条目以外的条目时会出现错误?
- c++ - 为什么这个结构的大小看起来应该是 12/24 时却是 40?
- c# - 使用 Windows 窗体应用程序保存和加载用户在 c# 中添加的列表框项目
- java - 如何知道二进制文件的字节数?
- c++ - 双参数模板
- jquery - 在 Wordpress 中运行 jQuery Functions Document Ready & Window Resize