Append columns of dataframe to list as lists

Viewed 53

I have a dataframe:

col1   col2  col3
1       7     8
1.5     6.7   9
1.24    5.5   8.8

I want to write a function, which will add these columns values as lists to a list. So there will be a nested list, with those values:

[[1,1.5,1.24], [7,6.7,5.5], [8,9,8.8]]

I wrote this function, but it doesn't work:

def func1(df):
    my_list=[]
    for i in df:
        my_list.append(i)
3 Answers

Here is the solution. you just change your data frame name to 'df':

lst=[]
for i in range(len(df.columns)):
    takelists = df.iloc[:, i].tolist()
    lst.append(takelists)

print(last)

Example:

  Column Column2 Column3
0   1      4       7
1   2      5       8
2   3      6       9

Out[129]:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can do this by combining to_numpy() and tolist method:

values = df.to_numpy().T.tolist()
print(values)

Output:

[[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]

Pandas DataFrame can be converter to Python list with calling x.tolist(). You can also use list(x)

import pandas as pd

datadict = {'col1': [1, 1.5, 1.24], 'col2': [7, 6.7, 5.5], 'col3': [8, 9, 8.8]}
df = pd.DataFrame(datadict)

print(f"DataFrame:\n{df}")

# 1st way:
def func1(df_):
    my_list = list()
    for col in df_.columns:
        my_list.append(df_[col].tolist())
    return my_list

result1 = func1(df)
print(f"Using x.tolist():\n{result1}")

# 2nd way:
func2 = lambda df_: [list(df_[col]) for col in df_.columns]

result2 = func2(df)
print(f"Using list(x):\n{result2}")

Output:

DataFrame:
   col1  col2  col3
0  1.00   7.0   8.0
1  1.50   6.7   9.0
2  1.24   5.5   8.8

Using x.tolist():
[[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]

Using list(x):
[[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]
Related