alex
alex

Reputation: 41

How to extract element of pandas list column specified in other column?

I have a Pandas dataframe with two columns:

Sample input:

df = pd.DataFrame({
    'col1' : [['A', 'B'], ['C', 'D', 'E'], ['F', 'G']], 
    'col2' : [0, 2, np.nan]})

Expected output:

df_out = pd.DataFrame({
    'col1' : [['A', 'B'], ['C', 'D', 'E'], ['F', 'G']], 
    'col2' : [0, 2, np.nan],
    'col3' : ['A', 'E', np.nan]})

Upvotes: 0

Views: 53

Answers (2)

user16836078
user16836078

Reputation:

You can do a list comprehension to compare the two columns too.

df['col3'] = [i[int(j)] if not np.isnan(j) else j for i,j in zip(df.col1,df.col2)]

        col1  col2 col3
0     [A, B]   0.0    A
1  [C, D, E]   2.0    E
2     [F, G]   NaN  NaN

Upvotes: 0

anon01
anon01

Reputation: 11171

you can use a basic apply:

def func(row):
    if np.isnan(row.col2):
        return np.nan
    else:
        return row.col1[int(row.col2)]


df['col3'] = df.apply(func, axis=1)

output:

        col1  col2 col3
0     [A, B]   0.0    A
1  [C, D, E]   2.0    E
2     [F, G]   NaN  NaN

Upvotes: 2

Related Questions