I have a Dataframe which I want to transform into a multidimensional array using one of the columns as the 3rd dimension.
As an example:
我有一个Dataframe,我希望使用其中一列作为第三维转换为多维数组。举个例子:
df = pd.DataFrame({
'id': [1, 2, 2, 3, 3, 3],
'date': np.random.randint(1, 6, 6),
'value1': [11, 12, 13, 14, 15, 16],
'value2': [21, 22, 23, 24, 25, 26]
})
I would like to transform it into a 3D array with dimensions (id, date, values) like this:
The problem is that the 'id's do not have the same number of occurrences so I cannot use np.reshape()
.
我想将它转换为具有维度(id,日期,值)的3D数组,如下所示:问题是'id的出现次数不同,所以我不能使用np.reshape()。
For this simplified example, I was able to use:
对于这个简化的例子,我能够使用:
ra = np.full((3, 3, 3), np.nan)
for i, value in enumerate(df['id'].unique()):
rows = df.loc[df['id'] == value].shape[0]
ra[i, :rows, :] = df.loc[df['id'] == value, 'date':'value2']
To produce the needed result:
but the original DataFrame contains millions of rows.
要生成所需的结果:但原始DataFrame包含数百万行。
Is there a vectorized way to accomplice the same result?
是否有一种矢量化方式来帮助同样的结果?
1 个解决方案
#1
8
Approach #1
Here's one vectorized approach after sorting id
col with df.sort_values('id', inplace=True)
as suggested by @Yannis in comments -
这是使用@Yannis在评论中建议的使用df.sort_values('id',inplace = True)对id col进行排序后的一种向量化方法 -
count_id = df.id.value_counts().sort_index().values
mask = count_id[:,None] > np.arange(count_id.max())
vals = df.loc[:, 'date':'value2'].values
out_shp = mask.shape + (vals.shape[1],)
out = np.full(out_shp, np.nan)
out[mask] = vals
Approach #2
Another with factorize
that doesn't require any pre-sorting -
另一个不需要任何预分类的因子分解 -
x = df.id.factorize()[0]
y = df.groupby(x).cumcount().values
vals = df.loc[:, 'date':'value2'].values
out_shp = (x.max()+1, y.max()+1, vals.shape[1])
out = np.full(out_shp, np.nan)
out[x,y] = vals
#1
8
Approach #1
Here's one vectorized approach after sorting id
col with df.sort_values('id', inplace=True)
as suggested by @Yannis in comments -
这是使用@Yannis在评论中建议的使用df.sort_values('id',inplace = True)对id col进行排序后的一种向量化方法 -
count_id = df.id.value_counts().sort_index().values
mask = count_id[:,None] > np.arange(count_id.max())
vals = df.loc[:, 'date':'value2'].values
out_shp = mask.shape + (vals.shape[1],)
out = np.full(out_shp, np.nan)
out[mask] = vals
Approach #2
Another with factorize
that doesn't require any pre-sorting -
另一个不需要任何预分类的因子分解 -
x = df.id.factorize()[0]
y = df.groupby(x).cumcount().values
vals = df.loc[:, 'date':'value2'].values
out_shp = (x.max()+1, y.max()+1, vals.shape[1])
out = np.full(out_shp, np.nan)
out[x,y] = vals