Python/Pandas:如果列有多个值,则在lis中转换为具有多个值的单行

2024-09-25 16:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的数据帧中,我有许多相同的AutoNumber实例具有不同的KeyValue_String。我想将这些实例转换为一行,其中KeyValue_String是由多个唯一值组成的列表。在

    AutoNumber KeyValue_String  ReferralType                      Description
0        50899              DD             3                       Web Search
1        50905          Cheque             1            Gatestone Collections
2        50906              DD             2          Centum Mortgage Brokers
3        50907          Cheque             1     Financial Debt Recovery Ltd.
4        50908              DD             2          Centum Mortgage Brokers
5        50909              DD             2          Centum Mortgage Brokers
6        50910          Cheque             1      Allied International Credit
7        50911          Cheque             1              D&A Collection Corp
8        50912          Cheque             1            Gatestone Collections
9        50913          Cheque             1     Financial Debt Recovery Ltd.
10       50914          Cheque             3  Existing Customer - Refinancing
11       50914              DD             3  Existing Customer - Refinancing
12       50915          Cheque             1            Gatestone Collections
13       50916          Cheque             3  Existing Customer - Refinancing
14       50916          Cheque             3  Existing Customer - Refinancing

所需的输出将如下所示,但我希望保留所有其他列

^{pr2}$

Tags: 实例stringcustomercollectionsddfinancialexistingmortgage
1条回答
网友
1楼 · 发布于 2024-09-25 16:28:19

如果我理解正确,您可以选择使用^{}^{}和{a3}。在

df['KeyValue_String'] = df.groupby('AutoNumber').KeyValue_String.transform('unique')

然后,您可以删除重复项,假设在注释中提到,具有相同自动编号的行除了KeyValue_字符串外还包含重复信息。在

^{pr2}$

我建议如果你想要数组,你可以把列中的所有内容都作为一个数组来保存,而且不要花费精力在列中放置混合类型,这样做无论如何都很难使用。在

演示

>>> df
    AutoNumber KeyValue_String
0        50899              DD
1        50905          Cheque
2        50906              DD
3        50907          Cheque
4        50908              DD
5        50909              DD
6        50910          Cheque
7        50911          Cheque
8        50912          Cheque
9        50913          Cheque
10       50914          Cheque
11       50914              DD
12       50915          Cheque
13       50916          Cheque
14       50916          Cheque

>>> df['KeyValue_String'] = df.groupby('AutoNumber').KeyValue_String.transform('unique')

>>> df.drop_duplicates(subset='AutoNumber')

    AutoNumber KeyValue_String
0        50899            [DD]
1        50905        [Cheque]
2        50906            [DD]
3        50907        [Cheque]
4        50908            [DD]
5        50909            [DD]
6        50910        [Cheque]
7        50911        [Cheque]
8        50912        [Cheque]
9        50913        [Cheque]
10       50914    [Cheque, DD]
12       50915        [Cheque]
13       50916        [Cheque]

相关问题 更多 >