divingTobi
divingTobi

Reputation: 2300

Select certain elements from a dataframe column with a list

I have a dataframe with one column containing python lists. How can I access certain elements of that list, e.g. the first and second only:

import pandas as pd

df = pd.DataFrame({'a':[['a', 'b', 'c'], ['e', 'f', 'g']]})
           a
0  [a, b, c]
1  [e, f, g]

Desired output:

        a
0  [a, b]
1  [e, f]

I was looking into .apply(), but I cannot find the appropriate function to apply to the list to get out the items.

Upvotes: 1

Views: 202

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

With your shown samples, could you please try following.

import pandas as pd
df['a'] = df['a'].str[:2]

Result will be as follows:

    a
0   ['a', 'b']
1   ['e', 'f']

Upvotes: 3

Abhi_J
Abhi_J

Reputation: 2129

  1. Using .apply() and lambda:
df = pd.DataFrame({'a':[['a', 'b', 'c'], ['e', 'f', 'g']]})

df['a'] = df.apply(
    lambda row: row[0][:2],
    axis=1
)

print(df)
  1. Using list comprehension
df.a = [x[:2] for x in df.a]
print(df)

Output:

        a
0  [a, b]
1  [e, f]

Upvotes: 1

Related Questions