gpt4 book ai didi

python - 如何从数据框列值创建多个列表

转载 作者:行者123 更新时间:2023-12-01 07:15:10 25 4
gpt4 key购买 nike

df1

    Ticker          Category
0 XOM Group 1
1 CVX Group 1
2 RDSA-GB Group 2
3 BP-GB Group 1, Group 2
4 EQNR-NO Group 3
5 FP-FR Group 4
6 ENI-IT Group 3, Group 4
7 COP Group 5

我想要的结果将基于“类别”列和名称创建“股票代码”列表,列出“类别”值,同时用“_”替换空格

其次,如果存在类别有两个值的实例,例如“US Major、Euro Major”,那么我如何确保“Ticker”最终出现在两个类别列表中?

Group_1 = ['XOM','CVX','BP-GB']
Group_2 = ['RDSA-GB','BP-GB']
Group_3 = ['EQNR-NO','ENI-IT']
Group_4 = ['FP-FR','ENI-IT']
Group_5 = ['COP']

谢谢!

最佳答案

好吧,你说列出列表,我想你的意思是用字典的方式?如果是这种情况,请尝试以下操作:

import pandas as pd

df = pd.DataFrame([["XOM","US Major"],
["CVX","US Major"],
["RDSA-GB","Euro Major"],
["BP-GB","Euro Major"],
["EQNR-NO","Euro Major"]],columns=["Ticker","Category"])

df_to_lists = df.groupby("Category")["Ticker"].apply(list)
lists_to_dict = dict(df_to_lists)
print(lists_to_dict)

输出:

{'Euro Major': ['RDSA-GB', 'BP-GB', 'EQNR-NO'], 'US Major': ['XOM', 'CVX']}

如果您不需要字典,则 df_to_lists 输出:

Category
Euro Major [RDSA-GB, BP-GB, EQNR-NO]
US Major [XOM, CVX]
Name: Ticker, dtype: object

关于python - 如何从数据框列值创建多个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58012697/

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