[英]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.