我有多个数据帧。
E.g
0 dd aa
1 ff qq
2 ff gg
4 ff df是否可以找到"gg“,然后返回找到它的位置的列号。在上面的示例中,它将返回一个整数1
发布于 2019-03-05 19:42:36
将值与numpy.where进行比较,选择第二个元组,如果需要第一个匹配,则通过索引进行选择:
print (np.where(df == 'gg'))
(array([1], dtype=int64), array([1], dtype=int64))
print (np.where(df == 'gg')[1])
[1]
a = np.where(df == 'gg')[1][0]
print (a)
1如果可能,某些值可能不匹配,请使用带有iter的next返回第一个匹配值或默认值:
print (next(iter(np.where(df == 'gg')[1]), 'no match'))
1
print (next(iter(np.where(df == 'aaa')[1]), 'no match'))
no match发布于 2019-03-05 20:29:48
假设列可以有名称,您可以这样找到包含'gg‘的(第一个)列:
found = df.isin(['gg']).any()
column_name = found[found].index.values[0]
integer_index = df.columns.get_loc(column_name)这将查找df.isin(['gg']).any()在DataFrame中查找'gg‘,并列出包含的所有列。
然后使用found[found].index.values[0]提取第一个列名。
最后,通过在列列表中查找列名来提取列名的整数位置。
https://stackoverflow.com/questions/55002026
复制相似问题