首页 > 解决方案 > 将字典项目映射到熊猫系列时忽略大小写

问题描述

我有一本包含大约 10 个数据框的字典。键是数据框名称

dataFramesDict[sheet_1] = pd.DataFrame({'Date':['2007-05-30','2107-11-30','2207-05-20','2307-05-20'],'Value': [2.4,2.5,2.6,2.7],'Test': ['Height','Weight','Systolic Blood Pressure Measurement','Diastolic Blood Pressure Measurement']})

在此处输入图像描述

我要做的是创建一个名为unit但通过将其映射到熊猫系列 ( unit_dict) 的新列,这是一个熊猫系列,如下所示。Term是索引名称。

我试图避免区分大小写或降低两者。

在此处输入图像描述

下面的代码抛出错误

def add_units():
for k in dataFramesDict.keys():
    dataFramesDict[k]['unit'] = dataFramesDict[k]['Test'].str.lower().map(unit_dict.index.str.lower())
print("units are added to the measurements successfully")

标签: pythonpython-3.xpandasdataframedictionary

解决方案


用于torenamestr.lower索引:Serieslowercase

unit_dict = unit_dict.rename(str.lower)
dataFramesDict[k]['unit'] = dataFramesDict[k]['Test'].str.lower().map(unit_dict)

#alternative
unit_dict.index = unit_dict.index.str.lower()
dataFramesDict[k]['unit'] = dataFramesDict[k]['Test'].str.lower().map(unit_dict)

推荐阅读