在python pandas datafram中用整数字典替换字符串

2024-09-27 21:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下熊猫数据帧。在

        epi_week    state   loc_type    disease    cases    incidence
21835   200011      WY      STATE       MUMPS       2       0.40
21836   197501      WY      STATE       POLIO       3       0.76
21837   199607      WY      STATE       HEPATITIS   3       0.61
21838   197116      WY      STATE       MUMPS       6       1.73
21839   200048      WY      STATE       HEPATITIS   6       1.21

我试图用一个唯一的整数替换每个disease。例如'MUMPS'==1'POLIO'==2等。最终的数据帧应如下所示:

^{pr2}$

我使用以下代码:

# creating a dictionary     
disease_dic = {'MUMPS':1, 'POLIO':2, 'MEASLES':3, 'RUBELLA':4,
               'PERTUSSIS':5, 'HEPATITIS A':6, 'SMALLPOX':7, 
               'DIPHTHERIA':8}
data.disease = [disease_dic[item] for item in data.disease]

我收到以下错误:

KeyErrorTraceback (most recent call last)
<ipython-input-115-52394901c90d> in <module>()
----> 1 cdc.disease = [disease_dic[item2] for item2 in cdc.disease]

KeyError: 1

有谁能帮忙解决这个问题吗?非常感谢。在


Tags: 数据infordataitemstateepicdc
1条回答
网友
1楼 · 发布于 2024-09-27 21:35:08

使用apply。在

例如:

disease_dic = {'MUMPS':1, 'POLIO':2, 'MEASLES':3, 'RUBELLA':4,
               'PERTUSSIS':5, 'HEPATITIS A':6, 'SMALLPOX':7, 
               'DIPHTHERIA':8}
import pandas as pd
df = pd.DataFrame({"disease": disease_dic.keys()})
print(df["disease"].apply(lambda x: disease_dic.get(x)))

输出:

^{pr2}$

相关问题 更多 >

    热门问题