gpt4 book ai didi

python - 重命名 pandas 中的特定行

转载 作者:行者123 更新时间:2023-11-30 21:58:11 24 4
gpt4 key购买 nike

我想将我的数据集的两个作业重命名为“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 行数据进行相同的实验时,与以下职位“pastry Comis”和“pastry Chef”对应的所有行都消失了。或新类别“糕点”

# 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)

知道可能是什么问题吗?

最佳答案

您可以使用:

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 cook

注意:我认为您为第一条记录保留了一个空格,因此它没有替换预期的内容,因为您的工作解决方案做了同样的事情,我们可以使用 str.strip() 处理它们

关于python - 重命名 pandas 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55019180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com