kdba
kdba

Reputation: 433

How to select a specific element from a list of rows in python

I have the following series (df):

Index    Information
1        [2, A, C]
2        [3, B, C]
3        [4, C, H]
4        [5, D, H]
5        [6, E, H]
6        [7, F, H]

and I want a series that only extracts and stores the third value of each list :

Index    Information
1        [C]
2        [C]
3        [H]
4        [H]
5        [H]
6        [H]

If I try df[0][2], it correctly gives the required output [C].

however, if I try df[:][2], instead of giving

[C]
[C]
[H]
[H]
[H]
[H]

the output is

3        [4, C, H]

What should be the correct syntax for this?

Upvotes: 2

Views: 1318

Answers (2)

piRSquared
piRSquared

Reputation: 294526

pandas.Series.str

df.Information.str[2:3]

0    [C]
1    [C]
2    [H]
3    [H]
4    [H]
5    [H]
Name: Information, dtype: object

With assign

df.assign(Information=df.Information.str[2:3])

   Index Information
0      1         [C]
1      2         [C]
2      3         [H]
3      4         [H]
4      5         [H]
5      6         [H]

comprehension per @coldspeed

df.assign(Information=[l[2:3] for l in df.Information.tolist()])

   Index Information
0      1         [C]
1      2         [C]
2      3         [H]
3      4         [H]
4      5         [H]
5      6         [H]

Upvotes: 2

Toby Petty
Toby Petty

Reputation: 4690

Another alternative:

df["new_col"] = df["Information"].apply(lambda x: x[2])

Upvotes: 0

Related Questions