gpt4 book ai didi

Python 将单元格中的多个值拆分为多行

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

我想要得到的是将单元格的多个值分成多行,然后仅获取在fruit_weight列中具有较大数值的行。

我有以下格式:

fruit_type;fruit_color;fruit_weight
Apple|Banana;Red|Yellow;2|1
Orange;Orange;4
Pineapple|Grape|Watermelon;Brown|Purple|Green;12|1|15

期望的结果输出:

fruit_type;fruit_color;fruit_weight
Apple;Red;2
Orange;Orange;4
Watermelon;Green;15

我的想法是将单元格分成行,然后解析值以获得正确的值,但我不知道如何开始。

一些帮助将不胜感激。

编辑1:

#!/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
fileData = pd.read_csv('articles.csv',delimiter=';')
fileData.replace('', np.nan, inplace=True)
fileData.dropna(subset=['fruit_type','fruit_color','fruit_weight'], inplace=True)
fileData = fileData.applymap(lambda x: x.split('|'))
idx = fileData.index.repeat(fileData.fruit_weight.str.len())
fileData = fileData.apply(lambda x: pd.Series(np.concatenate(x.tolist())), 0)
print fileData
fileData.assign(idx=idx).groupby('idx', group_keys=False).apply(lambda x: x.sort_values('fruit_weight', ascending=False).head(1))

最佳答案

import pandas as pd
import numpy as np
import io

text = '''fruit_type;fruit_color;fruit_weight
Apple|Banana;Red|Yellow;2|1
Orange;Orange;4
Pineapple|Grape|Watermelon;Brown|Purple|Green;12|1|15'''

buf = io.StringIO(text)

df = pd.read_csv(buf, sep=';') # replace "buf" with your CSV filename
df = df.applymap(lambda x: x.split('|'))

df

fruit_type fruit_color fruit_weight
0 [Apple, Banana] [Red, Yellow] [2, 1]
1 [Orange] [Orange] [4]
2 [Pineapple, Grape, Watermelon] [Brown, Purple, Green] [12, 1, 15]

加载和设置后,使用 apply + pd.Series + np.concatenate 展平数据框。同时,创建一个索引,以便下一步轻松分组。

idx = df.index.repeat(df.fruit_weight.str.len())

idx
Int64Index([0, 0, 1, 2, 2, 2], dtype='int64')

df = df.apply(lambda x: pd.Series(np.concatenate(x.tolist())), 0)
df

fruit_type fruit_color fruit_weight
0 Apple Red 2
1 Banana Yellow 1
2 Orange Orange 4
3 Pineapple Brown 12
4 Grape Purple 1
5 Watermelon Green 15

现在,调用 groupby + apply 并从每个组中提取具有最高权重值的一行。

df.assign(idx=idx).groupby('idx', group_keys=False)\
.apply(lambda x: x.sort_values('fruit_weight', ascending=False).head(1))

fruit_type fruit_color fruit_weight idx
0 Apple Red 2 0
2 Orange Orange 4 1
5 Watermelon Green 15 2

关于Python 将单元格中的多个值拆分为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949229/

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