gpt4 book ai didi

python - 根据某些行/条件将表格格式化为多列

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

我需要根据某些条件从下面格式化一个新表。每个电子邮件列都分组在一起。不知道从哪里开始。:

email              node_id  title
test@gmail.com 123 Some, text 1
test@gmail.com 456 Some, text 2
test@gmail.com 789 Some, text 3
example@gmail.com 123 Some, text 1
example@gmail.com 767 Some, text 4
example@gmail.com 122 Some, text 5
进入:
email              n1   t1             n2      t2           n3     t3
test@gmail.com 123 Some,text 1 456 Some,text 2 789 Some, text 3
example@gmail.com 123 Some,text 1 767 Some,text 4 122 Some, test 5

最佳答案

使用 cumcount 分配一列,以便您可以对其进行 pivot,然后重命名这些列:

res = (df.assign(no=df.groupby("email")["node_id"].cumcount()+1)
.pivot(index="email", columns="no", values=["node_id", "title"]))

res.columns = [x+str(y) for x in ("n", "t") for y in range(1, 4)]

print (res)

n1 n2 n3 t1 t2 t3
email
example@gmail.com 123 767 122 Some, text 1 Some, text 4 Some, text 5
test@gmail.com 123 456 789 Some, text 1 Some, text 2 Some, text 3

关于python - 根据某些行/条件将表格格式化为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63740919/

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