gpt4 book ai didi

python - 有条件地将不同 DataFrame 中的聚合列连接到新的 DataFrame 中

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:27 25 4
gpt4 key购买 nike

我有几个具有以下结构的 DataFrame:

In [22]: arrays = [np.array(['A1', 'A1', 'A1', 'A1', 'A2', 'A2', 'A2', 'A2']),
....: np.array(['B1', 'B1', 'B2', 'B2', 'B1', 'B1', 'B2', 'B2']),
....: np.array(['C1', 'C2', 'C1', 'C2', 'C1', 'C2', 'C1', 'C2'])]
In [23]: df1 = pd.DataFrame(np.random.randint(10, size=(8, 4)), index=arrays)
In [24]: df1
Out[24]:
0 1 2 3
A1 B1 C1 2 7 3 4
C2 6 2 1 7
B2 C1 3 3 5 6
C2 9 6 3 6
A2 B1 C1 7 8 0 6
C2 6 3 1 6
B2 C1 9 3 8 2
C2 7 1 2 8

In [25]: df2 = pd.DataFrame(np.random.randint(10, size=(8, 4)), index=arrays)
In [26]: df2
Out[26]:
0 1 2 3
A1 B1 C1 7 2 5 2
C2 0 2 9 0
B2 C1 2 2 6 9
C2 4 6 3 8
A2 B1 C1 7 1 5 1
C2 6 2 2 6
B2 C1 5 8 1 6
C2 7 4 8 0

我想构造以下 DataFrame。

max 是“0”列子数组中的最大值;

nth 如果第一级索引值包含“1”,则为“2”列子数组中的第 0 个元素,否则为“3”列子数组中的第 0 个元素。

             df1       df2
max nth max nth
A1 B1 6 3 7 5
B2 9 5 4 6
A2 B1 7 6 7 1
B2 9 2 7 6

我尝试使用 df[0].groupby(level=[0, 1]).max() 来计算 maxdf[2 or 3 ].groupby(level=[0, 1]).nth(0) 计算 nth 但仍坚持使用索引值作为选择列 2 或 3 的条件进行串联。

最佳答案

这是我的起点(与您的代码相同,不同的随机值):

          0  1  2  3
A1 B1 C1 3 4 1 6
C2 6 3 4 5
B2 C1 8 3 5 1
C2 8 5 1 6
A2 B1 C1 8 7 0 6
C2 5 1 4 7
B2 C1 3 1 8 5
C2 7 1 7 8
<小时/>
df[0] = df.groupby(level=[0,1])[0].transform(max)

0 1 2 3
A1 B1 C1 6 4 1 6
C2 6 3 4 5
B2 C1 8 3 5 1
C2 8 5 1 6
A2 B1 C1 8 7 0 6
C2 8 1 4 7
B2 C1 7 1 8 5
C2 7 1 7 8

我找不到直接检查第一级中“1”的方法,因此我只是使用 reset_index 将其转换为列,然后使用字符串方法就相当容易了它。

df['one'] = df.reset_index().level_0.str.contains('1').values
df['nth'] = np.where( df.one, df[2], df[3] )

0 1 2 3 one nth
A1 B1 C1 6 4 1 6 True 1
C2 6 3 4 5 True 4
B2 C1 8 3 5 1 True 5
C2 8 5 1 6 True 1
A2 B1 C1 8 7 0 6 False 6
C2 8 1 4 7 False 7
B2 C1 7 1 8 5 False 5
C2 7 1 7 8 False 8

现在清理一切(其中一些可以早点完成,但我认为等到最后并将其全部合并起来更清楚):

df.iloc[0::2,[0,-1]].reset_index(level=2,drop=True).rename(columns={0:'max'})

max nth
A1 B1 6 1
B2 8 5
A2 B1 8 6
B2 7 5

我不确定您是否也在询问 concat,但它非常简单:

pd.concat( [df1,df2], axis=1)

关于python - 有条件地将不同 DataFrame 中的聚合列连接到新的 DataFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424154/

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