Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the dataframe:

col1   col2  col3

1       7     8

1.5     6.7   9

1.24    5.5   8.8

I want to write the function, which will add the column's values as lists to a list. So there will be the nested list, with those values:

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

I wrote the below function, but it is not working:

def func1(df):

    my_list=[]

    for i in df:

        my_list.append(i)

1 Answer

0 votes
by (36.8k points)

You can use the below solution. you need to 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]]

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...