如何在Python Pandas中对元素进行分组并将它们全部列出?

时间:2019-06-09 21:24:08

标签: python arrays pandas numpy

我有这样的东西:

time 0   1   2   3   4   5
Val1 32  12  56  45  3   67
Val2 60  34  2   5   13  90

我想要一个由3个值组成的子数组列表,如下所示:

dataset=   [
[["32", "12", "56"], ["45", "3", "67"]],
[["60", "34", "2"], ["5", "13", "90"]]
 ]

我该怎么办?这行仅显示行列表

df.values.tolist()

3 个答案:

答案 0 :(得分:1)

IIUC

df=df.set_index('time')
df.groupby(np.arange(df.shape[1])//3,axis=1).agg(lambda x : x.values.tolist()).values.tolist()
[[[32, 12, 56], [45, 3, 67]], [[60, 34, 2], [5, 13, 90]]]

答案 1 :(得分:0)

time 0   1   2   3   4   5 

Val1 32  12  56  45  3   67

Val2 60  34  2   5   13  90

import pandas as pd

data= [[0,32,60],[1,12,34],[2,56,2],[3,45,5],[4,3,13],[5,67,90]]

df = pd.DataFrame(data, columns = ["time","val1","val2"])

答案 2 :(得分:0)

首先将整个DataFrame转换为列表,然后将每个列表分成2个单独的列表。

df2=df.values.tolist() #Convert the DataFrame to List
lst_split=[]
for lst in df2:
    temp1=lst[:len(lst)//2] #Create First Half of the split
    temp2=lst[len(lst)//2:] #Create Second Half of the split
    lst_split.append(temp1)
    lst_split.append(temp2) #Appending to the Final list