Search code examples
pythonpandasdataframeenumerate

For loop in pandas dataframe using enumerate


I have a basic dataframe which is a result of a gruopby from unclean data:

 df:

Name1   Value1  Value2
A       10      30
B       40      50

I have created a list as follows:

Segment_list = df['Name1'].unique()
Segment_list 

array(['A', 'B'], dtype=object)

Now i want to traverse the list and find the amount in Value1 for each iteration so i am usinig:

for Segment_list in enumerate(Segment_list):
    print(df['Value1'])

But I getting both values instead of one by one. I just need one value for one iteration. Is this possible?

Expected output:

10
40

Solution

  • Option 1:

    import pandas as pd
    import numpy as np
    import random
    
    np.random.seed(365)
    random.seed(365)
    rows = 25
    data = {'n': [random.choice(['A', 'B', 'C']) for _ in range(rows)],
            'v1': np.random.randint(40, size=(rows)),
            'v2': np.random.randint(40, size=(rows))}
    
    df = pd.DataFrame(data)
    
    # groupby n
    for g, d in df.groupby('n'):
    #     print(g)               # use or not, as needed
        print(d.v1.values[0])    # selects the first value of each group and prints it
    
    [out]:  # first value of each group
    5
    33
    18
    

    Option 2:

    dfg = df.groupby(['n'], as_index=False).agg({'v1': list})
    
    # display(dfg)
       n                                   v1
    0  A  [5, 26, 39, 39, 10, 12, 13, 11, 28]
    1  B      [33, 34, 28, 31, 27, 24, 36, 6]
    2  C        [18, 27, 9, 36, 35, 30, 3, 0]
    

    Option 3:

    • As stated in the comments, your data is already the result of groupby, and it will only ever have one value in the column for each group.
    dfg = df.groupby('n', as_index=False).sum()
    
    # display(dfg)
    
       n   v1   v2
    0  A  183  163
    1  B  219  188
    2  C  158  189
    
    # print the value for each group in v1
    for v in dfg.v1.to_list():
        print(v)
    
    [out]:
    183
    219
    158
    

    Option 4:

    • Print all rows for each column
    dfg = df.groupby('n', as_index=False).sum()
    
    for col in dfg.columns[1:]:  # selects all columns after n
        for v in dfg[col].to_list():
            print(v)
    
    [out]:
    183
    219
    158
    163
    188
    189