我有一个看起来像下面的数据
data = [(datetime.datetime(2021, 2, 6, 18, 48, 18, 97962), u'London', u'New York', u'UPLOAD_LOW'), (datetime.datetime(2021, 2, 6, 18, 48, 18, 97962), u'Berlin', u'Tokyo', u'DOWNLOAD_HIGH'), (datetime.datetime(2021, 2, 6, 18, 47, 8, 209495), u'Paris', u'Toronto', u'DROP_LOW')]
这是装在大熊猫中的样子
date source destination issue
0 2021-02-06 18:48:18.097962 London New York UPLOAD_LOW
1 2021-02-06 18:48:18.097962 Berlin Tokyo DOWNLOAD_HIGH
2 2021-02-06 18:47:08.209495 Paris Toronto DROP_LOW
现在,我想将列中的值映射issue
到字典。使用pandasmap
函数pandas.Series.map可帮助完成工作。但是问题是字典中要映射的键仅包含部分列值。
这是我下面的字典
issue_short_form_map = {
"UPLOAD": "UP",
"MEMORY": "MEM",
"DOWNLOAD": "DN"
}
现在说我想issue
用上述字典映射列。通常这就是我要做的
df = pd.DataFrame(data)
df.columns = ["date", "source", "destination", "issue"]
# map the values in issue column to the dictionary. Anything that doesn't match, keep the original
df["issue"] = df["issue"].map(issue_short_form_map).fillna(df["issue"])
但是问题是issue
列中的值不直接与键匹配,而是只有一部分匹配(在拆分_
并获得第一部分之后)。
有什么办法可以_
对列值进行拆分并使其与字典映射起作用?任何不匹配的内容都应保持原样。
我的最终输出应如下所示
date source destination issue
0 2021-02-06 18:48:18.097962 London New York UP_LOW
1 2021-02-06 18:48:18.097962 Berlin Tokyo DN_HIGH
2 2021-02-06 18:47:08.209495 Paris Toronto DROP_LOW
您可以split
先发布问题列,仅使用映射转换第一部分,然后再添加其余部分:
splits = df['issue'].str.split('_')
short_issue = splits.str[0].map(issue_short_form_map).fillna(splits.str[0])
df['issue'] = short_issue + '_' + splits.str[1]
df
# date source destination issue
#0 2021-02-06 18:48:18.097962 London New York UP_LOW
#1 2021-02-06 18:48:18.097962 Berlin Tokyo DN_HIGH
#2 2021-02-06 18:47:08.209495 Paris Toronto DROP_LOW
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句