熊猫返回包含字符串的单元格位置

Piy*_*are 3 numpy dataframe pandas

我是数据分析的新手,我想找到包含输入字符串的单元格位置。

例子:

Price   | Rate p/lot |  Total Comm|
 947.2      1.25        CAD 1.25

 129.3      2.1         CAD 1.25

 161.69     0.8         CAD 2.00
Run Code Online (Sandbox Code Playgroud)

如何找到字符串“CAD 2.00”的位置。所需的输出是 (2,2)

jez*_*ael 5

Replace columns names to numeric by range, stack and for first occurence of value use idxmax:

d = dict(zip(df.columns, range(len(df.columns))))
s = df.rename(columns=d).stack()
a = (s == 'CAD 2.00').idxmax()
print (a)
(2, 2)
Run Code Online (Sandbox Code Playgroud)

If want check all occurencies use boolean indexing and convert MultiIndex to list:

a = s[(s == 'CAD 1.25')].index.tolist()
print (a)
[(0, 2), (1, 2)]
Run Code Online (Sandbox Code Playgroud)

Explanation:

Create dict for rename columns names to range:

d = dict(zip(df.columns, range(len(df.columns))))
print (d)
{'Rate p/lot': 1, 'Price': 0, 'Total Comm': 2}

print (df.rename(columns=d))
        0     1         2
0  947.20  1.25  CAD 1.25
1  129.30  2.10  CAD 1.25
2  161.69  0.80  CAD 2.00
Run Code Online (Sandbox Code Playgroud)

Then reshape by stack for MultiIndex with positions:

s = df.rename(columns=d).stack()
print (s)
0  0       947.2
   1        1.25
   2    CAD 1.25
1  0       129.3
   1         2.1
   2    CAD 1.25
2  0      161.69
   1         0.8
   2    CAD 2.00
dtype: object
Run Code Online (Sandbox Code Playgroud)

Compare by string:

print (s == 'CAD 2.00')
0  0    False
   1    False
   2    False
1  0    False
   1    False
   2    False
2  0    False
   1    False
   2     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

And get position of first True - values of MultiIndex:

a = (s == 'CAD 2.00').idxmax()
print (a)
(2, 2)
Run Code Online (Sandbox Code Playgroud)

Another solution is use numpy.nonzero for check values, zip values together and convert to list:

i, j = (df.values == 'CAD 2.00').nonzero()
t = list(zip(i, j))
print (t)
[(2, 2)]

i, j = (df.values == 'CAD 1.25').nonzero()
t = list(zip(i, j))
print (t)
[(0, 2), (1, 2)]
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

In [353]: rows, cols = np.where(df == 'CAD 2.00')

In [354]: rows
Out[354]: array([2], dtype=int64)

In [355]: cols
Out[355]: array([2], dtype=int64)
Run Code Online (Sandbox Code Playgroud)