Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

create list nest from each column of pandas dataframe in python

Here is simple of my dataframe

                  A    B     C    D    
Date                                                                         
1                 A1   B1    C1   D1 
2                 A2   B2    C2   D2 
3                 A3   B3    C3   D3 
4                 A4   B4    C4   D4 

so i want to create nest list like [[A1,A2,A3,A4],[B1,B2,B3,B4],....]

i use command like mylist = dataframe.value.tolist()

but it return [[A1,B1,C1,D1],[A2,B2,C2,D2]] instead

so is there a way to get nest list as i want?

#i use python 3.8.5 and pandas dataframe import data from yfinance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just transpose and then call values:

df.T.values.tolist()

[['A1', 'A2', 'A3', 'A4'],
 ['B1', 'B2', 'B3', 'B4'],
 ['C1', 'C2', 'C3', 'C4'],
 ['D1', 'D2', 'D3', 'D4']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...