gpt4 book ai didi

Python Pandas 使用文本文件创建 Dataframe

转载 作者:行者123 更新时间:2023-11-28 22:26:03 26 4
gpt4 key购买 nike

我正在尝试使用 Pandas 从原始文本文件创建数据框。该文件包括 3 个类别,类别名称后有与每个类别相关的项目。我能够基于类别创建一个系列,但不知道如何将每个项目类型关联到它们各自的类别并从中创建一个数据框。下面是我的初始代码以及所需的数据帧输出。能否请您帮助指导我以正确的方式执行此操作?

category = ['Fruits', 'Vegetables', 'Meats']

items='''Fruits
apple
orange
pear
Vegetables
broccoli
squash
carrot
Meats
chicken
beef
lamb'''

Category = pd.Series()

i = 0
for item in items.splitlines():
if item in category:
Category = Category.set_value(i, item)
i += 1
df = pd.DataFrame(Category)
print(df)

所需的数据帧输出:

Category    Item
Fruits apple
orange
pear
Vegetables broccoli
squash
carrot
Meats chicken
beef
lamb

最佳答案

使用:


category = ['Fruits', 'Vegetables', 'Meats']

items='''Fruits
apple
orange
pear
Vegetables
broccoli
squash
carrot
Meats
chicken
beef
lamb'''

df = pd.DataFrame({'Fruit':items.splitlines()})

mask = df['Fruit'].isin(category)
df.insert(0,'Category', df['Fruit'].where(mask).ffill())
df = df[df['Category'] != df['Fruit']].reset_index(drop=True)
print (df)
Category Fruit
0 Fruits apple
1 Fruits orange
2 Fruits pear
3 Vegetables broccoli
4 Vegetables squash
5 Vegetables carrot
6 Meats chicken
7 Meats beef
8 Meats lamb

如有必要,最后计算CategoriesFruits 使用groupbysize :

What is the difference between size and count in pandas?

df1 = df.groupby(['Category','Fruit']).size()
print (df1)
Category Fruit
Fruits apple 1
orange 1
pear 1
Meats beef 1
chicken 1
lamb 1
Vegetables broccoli 1
carrot 1
squash 1
dtype: int64

关于Python Pandas 使用文本文件创建 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45113619/

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