pythonpandas

How to slice list made columns


Imagine, i have a column made by a bunch of of lists.

Column A 
List A of userids
List B of userids
List C of userids
List D of userids

And i want to acess list A, through index. Normally, i would just do

df['Column A'][0]

End result should be:

['ELEMENT OF LIST A', 'ELEMENT OF LIST A']

But i get a weird keyerror : 0. Any ideas on what i could do so i get that specific end result? I want to know that because i need to acess a list value according to the index of my loop.

As asked here is the dict output of a single row. It was the best i could do considering the size of the suceding ones.

{'Steps': {0: '1-Onboarding + Retorno'},
 'CampaignSource': {0: 'abd-ecomm-sms'},
 'UserId': {0: [
   '07cf01d5-5179-4fa2-b3a1-a341cfa11625@tunnel.msging.net',
   '11f214d8-45dc-46d6-a9ae-8ae08a42cd7c@tunnel.msging.net',
   '2d24e127-a956-4946-af1f-47341761074b@tunnel.msging.net']}}

Solution

  • Assuming you have an index that doesn't contain 0, like say:

    df = pd.DataFrame(
        {'Column A': [['a', 'b', 'c'], ['d', 'e']]},
        index=['i', 'j'])
    
    #     Column A
    # i  [a, b, c]
    # j     [d, e]
    

    Doing df['Column A'][0] would try to access the index 0 of the Series, which doesn't exist and raises a KeyError.

    If you want to get all first items of the lists (as a Series) use:

    df['Column A'].str[0]
    

    output:

    i    a
    j    d
    Name: Column A, dtype: object
    

    To get the first element of the list at indices i/Column A:

    df.loc['i', 'Column A'][0]
    # 'a'
    

    and for the first element of the first list of Column A:

    df['Column A'].iloc[0][0]
    # 'a'