如何使用 numpy 或 pandas 创建(或更改)数组/列表的维度? [英] How to create (or change) the dimensions of an array/list using numpy or pandas?
问题描述
我正在尝试创建一个 Pandas DataFrame 来收集我拥有的所有内容,但是我在将 numpy 数组组合到列表中以创建单个数组时遇到了困难.
I'm trying to create a pandas DataFrame to collect everything I have but I'm having difficulty combining numpy arrays in a list to create a single array.
假设我有以下数据:
df0 = pd.DataFrame([[1,2],[2,2],[3,1],[4,4],[5,4]], columns = ['A','B'])
switch = [[1,3,4],[2,5]]
collect = []
for lists in switch:
mask = df0.A.isin(lists)
avg = df0[mask].mean().round(2)
collect.append(avg)
collect.append((avg[0]**2+avg[1]+2).round(2))
这会产生以下输出:
[A 2.67
B 2.33
dtype: float64,
11.46,
A 3.5
B 3.0
dtype: float64,
17.25]
但是,我想要以下输出:
However, I want the following output:
A B C
2.67 2.33 11.46
3.5 3.0 17.25
但我无法创建 2x3 矩阵,因为 len(collect) 是 4.我想我没有在 for 循环中以正确的方式使用 .append.如何创建一个数组(或列表),使 len(collect) 为 2 或 6?我在想如果它的长度为 2,我们可以简单地转置 collect 或者它的长度为 6,我们可以重塑它.
but I can't create a 2x3 matrix because len(collect) is 4. I think I'm not using .append in the right way in the for-loop. How do I create an array (or a list) such that len(collect) is either 2 or 6? I'm thinking if it's of length 2, we can simply transpose collect or of it's of length 6, we can reshape it.
推荐答案
我的方法:
(df0.groupby(pd.Series({x-1:k for k,v in enumerate(switch) for x in v}))
.mean()
.assign(C=lambda x: x['A']**2 + x['B']+2)
.round(2)
)
输出:
A B C
0 2.67 2.33 11.44
1 3.50 3.00 17.25
这篇关于如何使用 numpy 或 pandas 创建(或更改)数组/列表的维度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!