gpt4 book ai didi

python - 将 Pandas 值组合到成员组中

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:53 25 4
gpt4 key购买 nike

我正在尝试将两个 Pandas 列中的数字关联到成员资格组中。这是我目前所拥有的:

import pandas as pd
df = pd.DataFrame({'A':[0, 1, 3, 4, 6, 7, 8, 8, 8, 9, 9, 9, 9, 9, 11, 12, 13, 14, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 21, 22, 24, 25, 26, 27, 28, 29, 29],
'B':[1, 0, 4, 3, 7, 6, 112, 9, 114, 134, 135, 112, 8, 114, 14, 13, 12, 11, 16, 17, 18, 17, 15, 18, 19, 16, 18, 15, 19, 17, 16, 15, 19, 20, 20, 18, 17, 16, 19, 18, 22, 21, 25, 24, 27, 26, 29, 28, 30]})

df = df.groupby('A')['B'].apply(lambda x: list(set(x))).reset_index()

^ 信用 jezrael

df['A']=df['A'].apply(lambda x : [x])
df_new=pd.DataFrame((df['A'] + df['B']),columns=["Combined"])
df_new["Combined"]=df_new["Combined"].sort_values().apply(lambda x: sorted(x))

将 A 列中的数字和 B 中分组的值组合并排序。

                       Combined
0 [0, 1]
1 [0, 1]
2 [3, 4]
3 [3, 4]
4 [6, 7]
5 [6, 7]
6 [8, 9, 112, 114]
7 [8, 9, 112, 114, 134, 135]
8 [11, 14]
9 [12, 13]
10 [12, 13]
11 [11, 14]
12 [15, 16, 17, 18]
13 [15, 16, 17, 18, 19]
14 [15, 16, 17, 18, 19]
15 [15, 16, 17, 18, 19, 20]
16 [16, 17, 18, 19, 20]
17 [18, 19, 20]
18 [21, 22]
19 [21, 22]
20 [24, 25]
21 [24, 25]
22 [26, 27]
23 [26, 27]
24 [28, 29]
25 [28, 29, 30]

如何删除 df_new 中的重复列表。也许可以将列表转换为字符串值?

最重要的是,我想从原始 col_A 中获取每个值,并将其与它所属的组合列表中最具包容性的一个相关联。 因此,df 的 col_A 中的数字 8 应该与 df_new 中 Combined 列的第 7 行相关联,该行具有数字 8 的最包容列表 - [8, 9, 112, 114, 134, 135]。

谢谢你的帮助

最佳答案

我建议将您的 DataFrame 转换为 numpy 矩阵,使用 np.unique 方法获取唯一列表的矩阵,然后像这样转换回 DataFrame:

df_new["Combined"] = pd.DataFrame(np.unique(df_new.as_matrix()))

# 0
# 0 [0, 1]
# 1 [3, 4]
# 2 [6, 7]
# 3 [8, 9, 112, 114]
# 4 [8, 9, 112, 114, 134, 135]
# 5 [11, 14]
# 6 [12, 13]
# 7 [15, 16, 17, 18]
# 8 [15, 16, 17, 18, 19]
# 9 [15, 16, 17, 18, 19, 20]
# 10 [16, 17, 18, 19, 20]
# 11 [18, 19, 20]
# 12 [21, 22]
# 13 [24, 25]
# 14 [26, 27]
# 15 [28, 29]
# 16 [28, 29, 30]

关于python - 将 Pandas 值组合到成员组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49431973/

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