gpt4 book ai didi

python - 如何将 df 的多列拆分为多行?

转载 作者:行者123 更新时间:2023-12-04 04:08:54 25 4
gpt4 key购买 nike

我最近开始学习python。我的 df 看起来像:

**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple 5 65 50
Kiwi 8 80 65
Orange 6 70 55
Apple/Kiwi/Orange 9 65/80/70 50/65/55
Apple 4 50 40
Orange 7 65 45

我想让我的 df 看起来像:

**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple 5 65 50
Kiwi 8 80 65
Orange 6 70 55
Apple 9 65 50
Kiwi 9 80 65
Orange 9 70 55
Apple 4 50 40
Orange 7 65 45

我如何实现这一目标?

最佳答案

#convert to lists
res = df.astype('str').to_numpy().tolist()

#split each entry using "/"
res1 = [[val.split("/") for val in ent]
for ent in res]


#get the maximum length for each sublist
lengths = [max(len(v) for v in ent) for ent in res1]

#if the length of a value in a sublist is
#less than the maximum length,
# increase its length
res2 = [[v*length
if len(v) < length else v
for v in ent]
for ent,length
in zip(res1,lengths)
]

#zip through each sublist and chain the final outcome
final = chain.from_iterable(zip(*ent) for ent in res2)

#read back into dataframe
output = pd.DataFrame(final,columns=df.columns)
output


**FRUITS** **QUANTITY** **MARKET_PRICE** **SELLING_PRICE**
0 Apple 5 65 50
1 Kiwi 8 80 65
2 Orange 6 70 55
3 Apple 9 65 50
4 Kiwi 9 80 65
5 Orange 9 70 55
6 Apple 4 50 40
7 Orange 7 65 45

关于python - 如何将 df 的多列拆分为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62083474/

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