Snook55
Snook55

Reputation: 13

For Loop turn Dataframe Columns into individual lists

I am trying to take my locations data frame with 24 columns each with varying number of rows with data and turn each column into its own list. The goal is to define each column as its own list with the .tolist() method.

I know that I can do this by individually defining each list as

column_name1_list = locations['coumn_name1'].tolist()

However, I don't want to do this 24 times. I would like to use a loop to iterate over all the columns and create a list from each with the name of the column as the name of the list + "_list" added to the end.

This seems simple but my lack of experience with For Loops is definitely getting in the way. Any advice and explanation are greatly appreciated.

This is what I have so far and it's not working

for column in locations:
     locations[column] + "_list" = locations[column].tolist()

Then once those columns have all been turned into lists I would like to search another data frame's column for the items in each list. For this, I plan to use the following code

column_name1_final = df.loc[df['PARID'].isin(column_name1_list)]

But again, I feel it's unnecessary to do this 24 times over and a loop should be possible.

Thank you in advance for any and all help or suggestions.

Upvotes: 0

Views: 766

Answers (2)

Avishka Gimhana
Avishka Gimhana

Reputation: 1

I can get answer using following code:

df_column=[i for i in df.columns]

Upvotes: 0

jezrael
jezrael

Reputation: 863166

In my opinion here is possible create dictionary of lists by DataFrame.to_dict:

d = locations.to_dict(orient='list')

Then is possible get each list by selecting by key, here column name:

print (d['col1'])
print (d['col2'])

Sample:

locations = pd.DataFrame({
         'A':[5,20],
         'B':[10,25],
         'C':[15,30]
})

d = locations.to_dict(orient='list')
print (d)
{'A': [5, 20], 'B': [10, 25], 'C': [15, 30]}

print (d['A'])
[5, 20]

print (d['B'])
[10, 25]

Upvotes: 1

Related Questions