'Finding value in list in pandas column by index
I have a dataframe with many columns that are lists of values, which are floats. I would like to find the element or elements in these lists based on an index, which is an integer or integers in a separate column. Eg.
Results Index_1 Index_2
0 [2.347, 140.8, 1010.8, 723.7, 7, 0, 2.898, 9.1... 0 [0, 4, 6]
1 [93794, 112.7, 5.014, 0, 1778.1, 3473.82, 0, 3... 1 [1, 5]
2 [2.927, 12.647, 9047, 0, 1204.5, 13.4, 6.3, 4.... 2 [2, 0]
3 [0, 1.801, 7.104, 2121.2, 20.375, 6.348, 11.35... 2 [2, 9, 3]
What I would like is to create two columns with the values of the results based on Index and Index_2. Eg.
Results Index_1 Index_2 Outcome Outcome_2
0 [2.347, 140.8, 1010.8, 723.7, 7, 0, 2.898, 9.1... 0 [0, 4, 6] 2.347 [2.347, 7, 2.898]
1 [93794, 112.7, 5.014, 0, 1778.1, 3473.82, 0, 3... 1 [1, 5] 112.700 [112.7, 3473.82]
2 [2.927, 12.647, 9047, 0, 1204.5, 13.4, 6.3, 4.... 2 [2, 0] 9047 [9047, 2.927]
3 [0, 1.801, 7.104, 2121.2, 20.375, 6.348, 11.35... 2 [2, 9, 3] 7.104 [7.104, 12531.5, 20.375]
The Results vary in number and so does one of the indexes.
For some reason the index function does not work and I get thrown errors including:
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
This is when I run df['Outcome'] = df['Results'].index['Index_1']. I've played around with the code but cannot seem to get this to work.
I have checked the dtypes of the columns and they return list for Results and numpy.int64 for Index_1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
