Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from list according to index number

Tags:

python

pandas

I have been struggling to find the pandas solution to this without looping:

input:

df = pd.DataFrame({'A' : [[6,1,1,1], [1,5,1,1], [1,1,11,1], [1,1,1,20]]})

                A
0   [6, 1, 1, 1]
1   [1, 5, 1, 1]
2   [1, 1, 11, 1]
3   [1, 1, 1, 20]

output:

                A   B
0   [6, 1, 1, 1]    6
1   [1, 5, 1, 1]    5
2   [1, 1, 11, 1]   11
3   [1, 1, 1, 20]   20

I have tried so many different things over the past hour or so, and I know the solution will be an embarrassingly simple one-liner. Thanks for your help -- not my python day today!

like image 560
David Erickson Avatar asked Sep 19 '20 05:09

David Erickson


People also ask

How do you return an index from a specific value in a list Python?

The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.

What operator will return the index of a value in a list?

To fix this issue, you need to use the in operator. The in operator returns True if a value is in the list.


1 Answers

You can do a simple list comprehension:

df['B'] = [s[i] for i, s in zip(df.index, df['A'])]

Or if you want only diagonal values:

df['B'] = np.diagonal([*df['A']])

               A   B
0   [6, 1, 1, 1]   6
1   [1, 5, 1, 1]   5
2  [1, 1, 11, 1]  11
3  [1, 1, 1, 20]  20
like image 165
Shubham Sharma Avatar answered Oct 19 '22 23:10

Shubham Sharma