pandas 返回单元格位置包含字符串 [英] Pandas Return Cell position containing string
问题描述
我是数据分析的新手,我想找到包含输入字符串的单元格位置.
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
, 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)
如果要检查所有情况,请使用 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屋!