0

I'm trying to locate the column and index of each element in the 2D list, however I seem unable to do so. The 2D Array is the one below.

Top_Level_Data = [['Fund Code', 'Total Return ( Local )', 'Currency Return', 'Income Return', 'Total Return', 'Contrib. To Return', 'Bmark Total Return'], ['L09CBD', 1.99230092282758, 2.82574117438372e-06,
    0.215178694163583, 1.99230092282758, 1.99230380178837, 2.18128409041032]]

I am for example trying to get the following: Top_Level_Data.index('Fund Code')

However I am receiving errors such as 'Fund Code' is not in list. Could it be because the array contains different data types? Any help would be super appreciated. Thanks!

GCoxxx
  • 65
  • 7

2 Answers2

1

Try with numpy

>>> import numpy as np
>>> np.where(np.array(Top_Level_Data) == "Currency Return")
(array([0], dtype=int64), array([2], dtype=int64))

And flattened:

>>> np.array(np.where(np.array(Top_Level_Data) == "Currency Return")).ravel()
array([0, 2], dtype=int64)
>>> np.array(np.where(np.array(Top_Level_Data) == "Currency Return")).ravel()[0]
0
>>> np.array(np.where(np.array(Top_Level_Data) == "Currency Return")).ravel()[1]
2
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
1

It depends on what you want, in all cases, you can use a generator expression and use next to get the first element generated:

If you want the index of the sublist that contains 'Fund Code':

try:
    res = next(i for i, v in enumerate(Top_Level_Data) if 'Fund Code' in v)
except StopIteration:
    res = -1
# output: 0

If you want the index of 'Fund Code' in the sublist that contains it:

try:
    res = next(v.index('Fund Code') for v in Top_Level_Data if 'Fund Code' in v)
except StopIteration:
    res = -1
# output: 0

If you want both:

try:
    res = next((i, v.index('Fund Code')) for i, v in enumerate(Top_Level_Data) if 'Fund Code' in v)
except StopIteration:
    res = (-1, -1)
# output: (0, 0)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    `next(i for i, v in enumerate(Top_Level_Data) if 'Fund Code' in v)` raises `StopIteration` if the key is not present. +1 nevertheless – gboffi Sep 03 '19 at 11:35