Convert pandas Dataframe to multiple numpy array

Viewed 448

I want to convert my columns to multiple array in such a way that each row has values from same date

My data:

Date        Value
2006-12-11  816.2
2006-12-11  816.2
2006-12-11  816.2
2006-12-12  848.2
2006-12-12  849.0
2006-12-13  885.6
2006-12-13  887.0
2006-12-13  885.2
2006-12-13  882.0
2006-12-13  885.0

Expected output:

[[816.2, 816.2, 816.2]
[848.2, 849.0]
[885.6, 887.0, 885.2, 882.0, 885.0]] 
2 Answers

You can use groupby with numpy.array:

import numpy as np:

df.Value.groupby(df.Date).apply(np.array).values

Example:

df = pd.DataFrame({
    "Date": ['2006-12-11', '2006-12-11', '2006-12-11', '2006-12-12', '2006-12-12'], 
    'Value': [816.2, 816.2, 816.2, 848.2, 849.0]})
df.Value.groupby(df.Date).apply(np.array).values
array([array([816.2, 816.2, 816.2]), array([848.2, 849. ])], dtype=object)

You can convert values to list:

df.groupby(by=df.Date).agg(lambda x: x.tolist()).values
Related