Pandas dataframe:如何导出另一列中按值分组的值列表的列表



给定一个df:

timestamp   x_1  y_1   x_2  y_2
0  1649010310     1    4     7    7
1  1649010310     7    8     0    1
2  1649010310     5    1     0    0
3  1649010311     2    0     1    6
4  1649010311     8    4     2    7

我想导出按时间戳

分组的x_1, y_1, x_2, y_2坐标的列表有没有比在df中使用for循环更快的方法来导出一个列表的列表呢?

[[[1, 4, 7, 7],
[7, 8, 0, 1],
[5, 1, 0, 0]],
[[2, 0, 1, 6],
[8, 4, 2, 7]]]

?

当然我们可以像这样循环df:

for i in range(len(df)):
# create list of lists

但是,我想知道是否在pandas(或numpy?)中有更有效的东西可以使这个过程更快。

是的,您可以使用groupby并应用方法。

grouped = df.groupby('timestamp')
result = grouped[['x_1', 'y_1', 'x_2', 'y_2']].apply(lambda x: x.values.tolist())
result = result.tolist()

相关内容

最新更新