Reputation: 2300
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
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
Reputation: 2129
.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)
df.a = [x[:2] for x in df.a]
print(df)
Output:
a
0 [a, b]
1 [e, f]
Upvotes: 1