gpt4 book ai didi

numpy - 具有多索引到Numpy矩阵的Pandas DataFrame

转载 作者:行者123 更新时间:2023-12-04 04:10:35 24 4
gpt4 key购买 nike

我有一个带有2个索引的pandas DataFrame。 (MultiIndex)我想得到一个类似df.as_matrix(...)的Numpy矩阵,但是这个矩阵的形状为(n_rows, 1)。我想要一个形状为(n_index1_rows, n_index2_rows, 1)的矩阵。

有没有一种方法可以使用.groupby(...),然后使用.values.tolist().as_matrix(...)获得所需的形状?

编辑:数据

                                                              value  
current_date temp_date
1970-01-01 00:00:01.446237485 1970-01-01 00:00:01.446237489 30.497100
1970-01-01 00:00:01.446237494 9.584300
1970-01-01 00:00:01.446237455 10.134200
1970-01-01 00:00:01.446237494 7.803683
1970-01-01 00:00:01.446237400 10.678700
1970-01-01 00:00:01.446237373 9.700000
1970-01-01 00:00:01.446237180 15.000000
1970-01-01 00:00:01.446236961 12.928866
1970-01-01 00:00:01.446237032 10.458800

这是一个主意:
np.array([np.resize(x.as_matrix(["value"]).copy(), (500, 1)) for (i, x) in df.reset_index("current_date").groupby("current_date")])

最佳答案

我认为您想要的是拆开多索引,例如

df.unstack().values[:, :, np.newaxis]

编辑:如果您有重复的索引,则无法进行堆积,而您可能需要 pivot_table来代替:
pivoted = df.reset_index().pivot_table(index='current_date',
columns='temp_date',
aggfunc='mean')
arr = pivoted.values[:, :, np.newaxis]
arr.shape
# (10, 50, 1)

这是 unstack的完整示例。首先,我们将创建一些数据:
current = pd.date_range('2015', periods=10, freq='D')
temp = pd.date_range('2015', periods=50, freq='D')
ind = pd.MultiIndex.from_product([current, temp],
names=['current_date', 'temp_date'])
df = pd.DataFrame({'val':np.random.rand(len(ind))},
index=ind)
df.head()
# val
# current_date temp_date
# 2015-01-01 2015-01-01 0.309488
# 2015-01-02 0.697876
# 2015-01-03 0.621318
# 2015-01-04 0.308298
# 2015-01-05 0.936828

现在我们拆开多索引:我们将显示数据的第一个4x4切片:
df.unstack().iloc[:4, :4]
# val
# temp_date 2015-01-01 2015-01-02 2015-01-03 2015-01-04
# current_date
# 2015-01-01 0.309488 0.697876 0.621318 0.308298
# 2015-01-02 0.323530 0.751486 0.507087 0.995565
# 2015-01-03 0.805709 0.101129 0.358664 0.501209
# 2015-01-04 0.360644 0.941200 0.727570 0.884314

现在提取numpy数组,并按照问题中的指定将其整形为[nrows x ncols x 1]:
vals = df.unstack().values[:, :, np.newaxis]
print(vals.shape)
# (10, 50, 1)

关于numpy - 具有多索引到Numpy矩阵的Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33508026/

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