gpt4 book ai didi

python - 扩展分层数据,根据列中的列表项创建新行

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:23 24 4
gpt4 key购买 nike

我如何根据下面提供的关于嵌套组的条件来扩展数据框?

团体

Name                    Job        Group
[Matt,Adam,John,James] Peon Workers
[Sam,Andrew,John] Boss Leader
[Leader,Ian] Owner Owner

我怎样才能做出如下预期的输出:

预期输出:

Name    Job       Group
Matt Peon Workers
Adam Peon Workers
John Peon Workers
James Peon Workers
Sam Boss Leader
Andrew Boss Leader
John Boss Leader
Sam Owner Owner
Andrew Owner Owner
John Owner Owner
Ian Owner Owner

我当前的方法(不完全有效)提取所有用户,但不识别也等于组名的成员并为每个成员创建一个新条目。

groups.members.apply(lambda x: pd.Series(x)).stack().reset_index(level=1, drop=True).to_frame('members').join(groups[['Job', 'Group']], how='left')

最佳答案

我不确定这是否可以完全在 pandas 中完成。我在外部处理过相关数据,然后重新加入。

import pandas as pd

groups = pd.DataFrame({'Name': [['Matt','Adam','John','James'], ['Sam','Andrew','John', 'Boss']], 'Job': ['Peon', 'Owner'], 'Group': ['Boss', 'Leader']})

# Build a list of tuples with row to draw group and job from and name
x = [(idx, i) for idx, j in enumerate(groups['Name']) for i in j]

# Search the list for group names, if found resolve group
# names to additional members of row where group was found
for i, j in x:
if j in set(groups.Group):
x.remove((i, j))
for n in list(*list(groups['Name'][groups.Group == j])):
x.append((i, n))

# Create new DataFrame
idx, names = zip(*x)
z = pd.DataFrame(list(names), index=list(idx))

# Join on the old one
groups = groups.drop('Name', axis=1).join(z)

关于python - 扩展分层数据,根据列中的列表项创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893336/

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