简体   繁体   中英

How can I get a nested list by year?

I have a DataFrame that looks like this:

(Columns are month numbers)

     Year    level_0    1           2           3
0   1950    Prec    1.176959    2.422704    1.911290
1   1950    TempMax 14.752511   16.801811   19.213571
2   1950    TempMed 10.168848   12.086479   14.225829
3   1950    TempMin 5.883087    7.504439    9.417972
4   1951    Prec    4.294701    4.976021    4.160138
(...)

How do I get a nested list, where each element of the list is a matrix with 4 rows (Prec,TempMax,TempMed,TempMin) and 3 columns (1,2,3) and a matrix for each year (but not including the year and the Level_O column)?

Output Example: [[[1.176959, 2.422704, 1.911290],[14.752511, 16.801811, 19.213571],[10.168848, 12.086479, 14.225829],[5.883087, 7.504439, 9.417972]],[...],[...]]

Use DataFrame.groupby by years with convert columns to lists per groups in lambda function:

Notice: If columnsnames are strings use ['1','2','3']

L = df.groupby('Year')[[1,2,3]].apply(lambda x: x.to_numpy().tolist()).tolist()

Or in list comprehension:

L = [x[[1,2,3]].to_numpy().tolist() for i, x in df.groupby('Year')]

print (L)
[[[1.176959, 2.422704, 1.91129], 
  [14.752511, 16.801811, 19.213571], 
  [10.168848, 12.086479, 14.225829], 
  [5.883087, 7.504439, 9.417972]],
 [[4.294701, 4.976021, 4.160138]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM