python - Python中的大小写转换
问题描述
我正在寻找与 SQL 中的 case 等效的 python 功能。基本上我的数据框中有类别数据,我想转换如下所示的内容。
Case when Column='X' then 'A' when Column='Y' then 'B' End.
Python中是否有任何等效功能?
解决方案
您可以使用 pandas 内置函数“replace”,提供一个字典,其中 key 是要替换的标签,value 是要替换的标签:
df =pd.DataFrame({'Data': [1, 2, 3, 4, 5],
'Labels': ['X', 'Y', 'Y', 'X', 'Y']})
df['Labels'] = df['Labels'].replace({'X': 'A', 'Y': 'B'})
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html
编辑:
对于更详细的替换,如果您知道要替换的确切字符串,您可以像上面那样写,例如 {'BHK Apartment': Apartment'}。否则,如果您想替换任何包含子字符串的字符串,例如'Villa',您可以使用正则表达式:
df =pd.DataFrame({'Data': [4, 4, 2],
'Labels': ['BHK Apartment', 'BHK Villa', 'BHK PentHouse']})
df['Labels'] = df['Labels'].replace({r'.*Apartment$': 'Apartment', r'.*Villa$': 'Villa', r'.*PentHouse$': 'PentHouse'}, regex=True)
推荐阅读
- python - 我正在尝试向 send.keys 发送我计算的值,然后单击保存按钮,但该值没有保存,这是为什么呢?
- firebase - 删除用户时不会触发 Firebase 云功能
- r - 在 R 中匹配和合并具有不同列名的数据集
- grails - 如何使用 List 填充 Grails 域类
- batch-file - .bat 管道对 cmd 提示的多个响应
- javascript - 其他通过html与node.js连接显示mysql的方式
- multithreading - Julia (1.3) 中斐波那契数列的多线程并行性能问题
- selenium - 远程服务器中的robotframework打开浏览器不能从网页工作
- python - 任何带有非散列参数缓存装饰器的python库?
- r - 运动 R 功能问题;否则-如果?