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

时间:2018-04-05 10:07:50

标签: pandas numpy dataframe

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

示例:

forRoot

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

3 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:2)

rangestack将列名称替换为数字,并且首次出现值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

a = s[(s == 'CAD 1.25')].index.tolist()
print (a)
[(0, 2), (1, 2)]

说明:

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

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 - 值的位置:

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

另一种解决方案是将numpy.nonzero用于检查值,将zip值合在一起并转换为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)]

答案 2 :(得分:1)

一个简单的替代方案:

def value_loc(value, df):
    for col in list(df):
        if value in df[col].values:
            return (list(df).index(col), df[col][df[col] == value].index[0])
相关问题