简体   繁体   English

如何用字典键替换数据框列值?

[英]How to replace dataframe column values with dictionary keys?

Suppose I have a dictionary: 假设我有一本字典:

dict = {"1" : "A", "2" : "B" , "3" : "C"}

and a data frame 和一个数据框架

df = pd.DataFrame()
df["ID"] = pd.Series(["A","B","C"])
df["Desc"] = pd.Series(["Fruits","Vegs","Meat"])

The dataframe will look like this: 数据框将如下所示:

在此输入图像描述

How would I replace values in column df["ID"] with dictionary keys so that I have 1,2,3 in df["ID"] instead of A,B,C ? 如何用字典键替换列df["ID"]值,以便我在df["ID"]1,2,3而不是A,B,C

First create a reverse mapping: 首先创建一个反向映射:

In [363]: dict2 = {v : k for k, v in dict_.items()}

The assumption made here is that your values are unique. 这里假设您的价值观是独一无二的。 Now you can use pd.Series.replace : 现在您可以使用pd.Series.replace

In [367]: df.ID = df.ID.replace(dict2); df
Out[367]: 
  ID    Desc
0  1  Fruits
1  2    Vegs
2  3    Meat

Alternative solution with pd.Series.map : pd.Series.map替代解决方案:

In [380]: df.ID = df.ID.map(dict2); df
Out[380]: 
  ID    Desc
0  1  Fruits
1  2    Vegs
2  3    Meat

Also, I recommend you use a different name than dict , because there's already a builtin with that name. 另外,我建议你使用与dict不同的名称,因为已经有一个带有该名称的内置。

Or you can just base on pandas . 或者你可以只基于熊猫。

df.ID=df.ID.map((pd.DataFrame(data=d,index=['Value',]).T.reset_index().set_index('Value'))['index'])

Out[23]: 
  ID    Desc
0  1  Fruits
1  2    Vegs
2  3    Meat

Another way to do this would be: 另一种方法是:

dict1 = pd.DataFrame(dict.items())
dict1.columns = ['ID_1',"ID"]
merge = pd.merge(df,dict1)
del merge['ID']
merge = merge.rename(columns={'ID_1': 'ID'})

    Desc    ID
0   Fruits  1
1   Vegs    2
2   Meat    3

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

相关问题 如何用字典列表键替换 dataframe 列值? - How to replace dataframe column values with dictionary list keys? 如何用pandas中的字典键替换列值 - how to replace column values with dictionary keys in pandas 根据包含的字典键替换 Pandas DataFrame 列值 - Replace Pandas DataFrame column values based on containing dictionary keys 如何将带有字典值的 DataFrame 转换为其他 DataFrame,键作为列标题 - How to convert DataFrame with Dictionary Values into other DataFrame, keys as column header 如果值是列表,如何根据值将字典键转换为 dataframe 列 - How to transform dictionary keys into a dataframe column based on the values if the values are lists 字典键用字典值替换pandas dataframe列中的字符串并执行evaluate - dictionary keys to replace strings in pandas dataframe column with dictionary values and perform evaluate 如何根据字典键和值替换熊猫数据框列值? - How to replace pandas dataframe column values based on dictionary key and values? 如何将字典的键映射到 Pandas Dataframe 的列值 - how to map keys of the dictionary to a column values of pandas Dataframe 如何从字典中替换 dataframe 列中的特定值? - How to replace particular values in dataframe column from a dictionary? 如何用字典中的查找值替换 pandas DataFrame 列? - How to replace a pandas DataFrame column with lookup values from a dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM