Python 将dict项映射到系列时忽略大小写
我有一本包含大约10个数据帧的字典。其中key是数据帧名称Python 将dict项映射到系列时忽略大小写,python,python-3.x,pandas,dataframe,dictionary,Python,Python 3.x,Pandas,Dataframe,Dictionary,我有一本包含大约10个数据帧的字典。其中key是数据帧名称 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 M
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
的新列,但通过将其映射到pandas系列(unit\u dict
)就是pandas系列,如下所示<代码>术语是索引名称
我试图避免区分大小写,或者降低两者
下面的代码抛出错误
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")
使用
rename
和str.lower
作为系列
到小写
的索引:
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)
我可以知道为什么我们必须使用
重命名
?即使我使用了你提供的相同的备选答案,但它不起作用。但是在一行中though@SSMK-对我来说更整洁;)但如果你更喜欢另一种解决方案,两者应该以相同的方式工作