【问题标题】:Ignore case while mapping dict items to a pandas series将字典项目映射到熊猫系列时忽略大小写
【发布时间】:2019-12-13 01:44:03
【问题描述】:

我有一本包含大约 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 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")

【问题讨论】:

    标签: python python-3.x pandas dataframe dictionary


    【解决方案1】:

    使用renamestr.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)
    

    【讨论】:

    • 我可以知道为什么我们必须使用rename吗?甚至正在使用您提供的相同替代答案,但它不起作用。但是在一行中
    • @SSMK - 对我来说它更整洁;)但如果喜欢更多其他解决方案,两者应该以相同的方式工作
    猜你喜欢
    • 2019-09-28
    • 2020-09-25
    • 2021-04-30
    • 2019-07-30
    • 1970-01-01
    • 2019-05-06
    • 2021-05-03
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多