pandas 返回单元格位置包含字符串 [英] Pandas Return Cell position containing string

查看:72
本文介绍了 pandas 返回单元格位置包含字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to data analysis , I wand to find cell position which containing input string.

示例:

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

如何找到字符串"CAD 2.00"的位置. 要求的输出是(2,2)

How do I find position of string "CAD 2.00". Required output is (2,2)

推荐答案

range如果要检查所有情况,请使用 boolean indexing 并将MultiIndex转换为list:

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)]

说明:

创建dict以将列名称重命名为范围:

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

然后用stack重塑MultiIndex的位置:

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

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

并获取第一个True的位置-MultiIndex的值:

And get position of first True - values of MultiIndex:

a = (s == 'CAD 2.00').idxmax()
print (a)
(2, 2)

另一种解决方案是使用 numpy.nonzero 对于检查值,将zip值放在一起,然后转换为list:

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)]

这篇关于 pandas 返回单元格位置包含字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆