'Python data extraction : How to apply all the variables in the 'For Loop' to 'data frame.column.'

I would like to divide the DataFrame Based on the unique values of a particular column in the data frame. Before dividing the data frame, I made the list variable that applies it.

list1 = [a,b,c,d]
for name in list1[:]:
   Data = df.loc[(df['column_name'] == name)]

this code, only the last value of 'd' applies. How can I apply all the list1_variables through For Loop? On the other hand, Please let me know if there is a better way than For Loop!



Solution 1:[1]

As I posted in my comment to your question, it depends on what you ultimately want to do with Data. Following the code you've posted, I've included an example where Data is a list of dictionaries.

import pandas as pd

data = {
    'a': ['a', 'a', 'a', 'b', 'b', 'c'],
    'b': [1, 2, 3, 4, 5, 6]
}

df = pd.DataFrame(data)

data = []
for name in df['a'].unique():
    data.append(
        {name: [i for i in df.loc[(df['a'] == name)]['b']]}
    )

print(data)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sean Richards