gpt4 book ai didi

python - 我可以在 Pandas 中做这样的 str 操作吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:53 25 4
gpt4 key购买 nike

我使用 pandas 使我的数据看起来像下面代码中的字典。

我想找到所有的 salsa 类型,并将它们放入一个 dict 中,该 salsa 类型的项目数作为字典值。

这是用 Python 编写的。有没有办法在 Pandas 中做这样的事情?或者这个任务是我应该迭代并使用 plain-ole-Python 的地方吗?

#!/usr/bin/env python3
import pandas as pd

items_df = pd.DataFrame({'choice_description': {0: '[Tomatillo Red Chili Salsa, [Fajita Vegetables, Black Beans, Pinto Beans, Cheese, Sour Cream, Guacamole, Lettuce]]', 1: '[Tomatillo-Red Chili Salsa (Hot), [Black Beans, Rice, Cheese, Sour Cream]]', 2: '[Fresh Tomato Salsa (Mild), [Rice, Cheese, Sour Cream, Guacamole, Lettuce]]', 3: '[Tomatillo Red Chili Salsa, [Fajita Vegetables, Black Beans, Pinto Beans, Cheese, Sour Cream, Guacamole, Lettuce]]'}, 'item_name': {0: 'Chips and Fresh Tomato Salsa', 1: 'Chips and Tomatillo-Green Chili Salsa', 2: 'Chicken Bowl', 3: 'Steak Burrito'}})

salsa_types_d = {}

for row in items_df.itertuples():
for food in row[1:]:
fixed_foods_l = food.replace("and",',').replace('[','').replace(']','').split(',')
fixed_foods_l = [f.strip() for f in fixed_foods_l if f.find("alsa") > -1]
for fixed_food in fixed_foods_l:
salsa_types_d[fixed_food] = salsa_types_d.get(fixed_food, 0) + 1

print('\n'.join("%-33s:%d" % (k,salsa_types_d[k]) for k in sorted(salsa_types_d,key=salsa_types_d.get,reverse=True)))

"""
Output:

Tomatillo Red Chili Salsa :2
Fresh Tomato Salsa :1
Fresh Tomato Salsa (Mild) :1
Tomatillo-Green Chili Salsa :1
Tomatillo-Red Chili Salsa (Hot) :1

---
Thank you for any insight.

Marilyn
"""

最佳答案

这可以在不使用 for 循环的情况下完成,其中一种方法是通过堆叠列创建一个单独的 df,然后替换值之后删除不包含 alsa 的值。然后最后使用 value_counts 来获取频率。

new_df = items_df.stack().reset_index(drop=True)
.replace(['and', '\[', '\]'],[',', '',''], regex=True).str.split(',')
.apply(lambda x: pd.Series([i.lstrip() for i in x if 'alsa' in i]))[0].value_counts()

输出:

Tomatillo Red Chili Salsa          2Tomatillo-Green Chili Salsa        1Tomatillo-Red Chili Salsa (Hot)    1Fresh Tomato Salsa (Mild)          1Fresh Tomato Salsa                 1Name: 0, dtype: int64

关于python - 我可以在 Pandas 中做这样的 str 操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009662/

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