我想将数据集的两个作业重命名为"pastry“。我创建了一个字典,其中包含了新的名称,并列出了前面的类别。
# dataframe for artificial dataframe
salary = [100, 200, 125, 400, 200]
job = ["pastry Commis ", "line cook", "pastry Commis", "pastry chef", "line cook"]
# New categories
cat_ac = {"pastry": ["pastry Commis", "pastry chef"]}
df_test = pd.DataFrame({"salary": salary, "job": job})
df_test.head()然后
df_test.loc[df_test["job"].isin(cat_ac[list(cat_ac.keys())[0]]), "job"] = list(cat_ac.keys())[0]
df_test在这个小数据集上,一切都很正常,但是当我对40k行数据做同样的实验时,所有对应于以下作业的行--“糕点Comis”和“糕点厨师”--都被删除了。或新类别的“糕点”
# We read the lines with the new category
df.loc[df["job"].isin(["pastry"]), "job"]
Out: Series([], Name: job, dtype: object)
# We read the lines with the previous categories
df.loc[df["job"].isin(cat_baking[list(cat_baking.keys())[0]]), "job"]
Out: Series([], Name: job, dtype: object)知道有什么问题吗?
发布于 2019-03-06 09:31:11
您可以使用:
df_test.job.replace({i:k for i in v for k, v in cat_ac.items()})
0 pastry Commis
1 line cook
2 pastry
3 pastry
4 line cookNote__:我认为您为第一张记录保留了一个空间,所以它没有替换它,因为您的工作解决方案也是这样做的,我们可以使用str.strip()来处理它们。
发布于 2019-03-06 09:17:49
使用替换的dict替换使用regex模式:
for k, v in cat_ac.items():
pat = '|'.join(v)
df_test['job'] = df_test['job'].str.replace(pat, k, regex=True)发布于 2019-03-06 09:52:17
您也可以使用np.where
import numpy as np
df_test['job'] = np.where((df_test['job'].str.contains('pastry Commis')) | (df_test['job'].str.contains('pastry chef')), 'pastry', df_test['job'])https://stackoverflow.com/questions/55019180
复制相似问题