简体   繁体   中英

Create list of lists from pandas cells without index and column names

I am trying to create a row-wise nested list from a Pandas Dataframe. The important aspect is to get rid of the index and column names.

Assuming the following df:

test = pd.DataFrame({'0' : ['1','4','5','5'],
       '1' : ['4','1','12','10'],
       '2' : ['10','12','4','2'],
       '3' : ['2','10','10','4']})

    0   1   2   3  
0   1   4   10  2   
1   4   1   12  10
2   5   12  4   10 
3   5   10  2   4  

I want to get this:

alist = [[1,4,10,2], [4,1,12,10],[5,12,4,10],[5,10,2,4]]

Any Ideas?

Thanks in advance!

Edit:

This was not helpful as the index and column names are also derived from the Dataframe:

# Create an empty list 
Row_list =[] 


# Iterate over each row 
for index, rows in df.iterrows(): 
    # Create list for the current row 
    my_list =[rows.Date, rows.Event, rows.Cost] 

    # append the list to the final list 
    Row_list.append(my_list) 

# Print the list 
print(Row_list) 

pandas.DataFrame.values would help.

In your case,

test.astype('int').values

gives the result:

array([[ 1,  4, 10,  2],
       [ 4,  1, 12, 10],
       [ 5, 12,  4, 10],
       [ 5, 10,  2,  4]])

Or if you wish to transpose the dataframe, pandas.DataFrame.T would help:

test.astype('int').T.values

which gives the result as:

array([[ 1,  4,  5,  5],
       [ 4,  1, 12, 10],
       [10, 12,  4,  2],
       [ 2, 10, 10,  4]])

Well, you might not need the T.

test.to_numpy('int').tolist()

Output:

[[1, 4, 10, 2], [4, 1, 12, 10], [5, 12, 4, 10], [5, 10, 2, 4]]

Use T for transpose, the convert to numpy array and tolist :

test.T.values.tolist()

Output:

[['1', '4', '5', '5'],
 ['4', '1', '12', '10'],
 ['10', '12', '4', '2'],
 ['2', '10', '10', '4']]

If you need integers use to_numpy with dtype:

test.T.to_numpy('int').tolist()

Output:

[[1, 4, 5, 5], [4, 1, 12, 10], [10, 12, 4, 2], [2, 10, 10, 4]]

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