首页 > 解决方案 > Python中的大小写转换

问题描述

我正在寻找与 SQL 中的 case 等效的 python 功能。基本上我的数据框中有类别数据,我想转换如下所示的内容。

Case when Column='X' then 'A' when Column='Y' then 'B' End.

Python中是否有任何等效功能?

标签: pythonpandas

解决方案


您可以使用 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)

https://kanoki.org/2019/11/12/how-to-use-regex-in-pandas/


推荐阅读