简体   繁体   English

基于字符串查找字典创建一个新的 python dataframe 列

[英]Create a new python dataframe column based on a dictionary of strings lookup

I have the following dataframe:我有以下 dataframe:

import pandas as pd    
df = pd.DataFrame({"bpstage": ["Normal", "Stage1", "Elevated", "Normal"]})

which lists a classification of blood pressure readings as strings, and I also have a strings dictionary listing all possible blood pressure classifications and for each an Hex code of the color I want to plot them to:它将血压读数的分类列为字符串,我还有一个字符串字典,列出所有可能的血压分类,并且对于每个颜色的十六进制代码,我想将它们 plot 到:

bp_stages = {
    "normal": "#aecd55",
    "elevated": "#fcec4f",
    "stage1": "#f4b93f",
    "stage2": "#ad451d",
    "crisis": "#8c1e1b",
}

my goal is to add a new column/series to the dataframe, say we call it bpcolor, and for each bpstage column row choose the corresponding color from the dictionary and fill that value in the corresponding bpcolor row.我的目标是在 dataframe 中添加一个新的列/系列,假设我们称之为 bpcolor,并为每个 bpstage 列行从字典中选择相应的颜色并将该值填充到相应的 bpcolor 行中。

Tried the following尝试了以下

df["bpcolor"] = df["bpstage"]
df["bpcolor"].map(bp_stages)

but only get NaNs.但只得到NaN。 Found similar solutions here with numeric values and those seem to work.在此处找到具有数值的类似解决方案,并且这些解决方案似乎有效。 Why is the case with strings not?为什么不是字符串的情况? Thank you谢谢

Problem is that word doesn't match between dictionary key and column value because of uppercase and lowercase, you can lowercase all values in bpstage column then map问题是由于大写和小写,字典键和列值之间的单词不匹配,您可以将bpstage列中的所有值小写,然后map

df["bpcolor"] = df["bpstage"].str.lower().map(bp_stages)
print(df)

    bpstage  bpcolor
0    Normal  #aecd55
1    Stage1  #f4b93f
2  Elevated  #fcec4f
3    Normal  #aecd55

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据复杂的字典为 dataframe 创建一个新列 - Create a new column for a dataframe based on a complicated dictionary 使用基于现有列和字典的值创建新的数据框列? - Create new dataframe column with values based existing column AND on dictionary? 根据列和另一个字典中的索引列表创建新的 dataframe 列 - Create new dataframe columns based on lists of indices in a column and another dictionary 基于 Python Pandas 中的几个查找表创建一个新列 - Create a new column based on several lookup tables in Python Pandas 通过使用基于另一个 dataframe 的查找替换逗号分隔列的值来创建新列 - Create a new column by replacing comma-separated column's values with a lookup based on another dataframe 根据特定列中存在的NaN在python数据框中创建一个新列 - Create a new column in python dataframe based on the presence of NaN in a specific column 基于字典向 dataframe 添加新列 - Add new column to dataframe based on dictionary 使用字符串列表或字典创建基于数据框中现有列的新列 - Using a List or Dictionary of Strings to create a new column based on an existing column within a Data frame 如何比较数据框列中的字符串值和单元格中的值以基于多值字典创建新的数据框? - How to compare string value in dataframe column and value in cell to create new dataframe based on multi value dictionary? Python:根据DataFrame中的列名创建新行 - Python: create new row based on column names in DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM