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!
The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.
To fix this issue, you need to use the in operator. The in operator returns True if a value is in the list.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With