在列表中查找列表索引的优雅方法?

时间:2019-04-29 23:24:52

标签: python-3.x list csv for-loop

python的新手。我正在尝试按行/列索引CSV文件中的项目。我发现的唯一方法是实现for循环以搜索列表中的每一行。

readCSV = [['', 'A', 'B', 'C', 'D'],
          [1.0, 3.1, 5.0, 1.7, 8.2],
          [2.0, 6.2, 7.0, 2.2, 9.3],
          [3.0, 8.8, 5.5, 4.4, 6.0]]

row_column = []
for row in readCSV:
    if my_item in row:
        row_column.append(row[0])
        row_column.append(readCSV[0][row.index(my_item)])

因此,对于my_item = 6.2,我得到row_column = [2.0, 'A']

这很好,但是我不禁想到有一个更优雅的解决方案。

2 个答案:

答案 0 :(得分:0)

尝试这个:

result = [(i, j) for i, k in enumerate(readCSV) for j, n in enumerate(k) if my_item == n]

答案 1 :(得分:0)

import pandas as pd
import numpy as np

df = pd.DataFrame(readCSV[1:],columns=readCSV[0])
#### Output ####
    No    A    B    C    D
0  1.0  3.1  5.0  1.7  8.2
1  2.0  6.2  7.0  2.2  9.3
2  3.0  8.8  5.5  4.4  6.0


##This provides the row in which there is a hit.
df1 = df[(df.A == my_item) | (df.B == my_item) |(df.C == my_item) | (df.D == my_item)]
print(df1)

#### Output ####
    No    A    B    C    D
1  2.0  6.2  7.0  2.2  9.3


##If you want only those column values which is a hit for your my_item.
z1 = pd.concat([df[df['A'] == my_item][['No','A']],df[df['B'] == my_item][['No','B']],df[df['C'] == my_item][['No','C']],df[df['D'] == my_item][['No','D']]])
print(z1)

#### Output ####
     A   B   C   D   No
1  6.2 NaN NaN NaN  2.0


## Incase if you want drop the nan , you can use np.isnan
z1 = np.array(z1)
print(z1[:,~np.any(np.isnan(z1), axis=0)])

#### Output ####
[[6.2 2. ]]