我有以下DataFrame:
a b c
b
2 1 2 3
5 4 5 6
如您所见,列b
用作索引。我想要获得满足('b' == 5)
的行的序号,在本例中应该是1
。
被测试的列可以是索引列(如本例中的b
),也可以是常规列,例如,我可能想要查找满足('c' == 6)
的行的索引。
发布于 2013-08-13 09:38:31
您可以像这样使用np.where:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(1,7).reshape(2,3),
columns = list('abc'),
index=pd.Series([2,5], name='b'))
print(df)
# a b c
# b
# 2 1 2 3
# 5 4 5 6
print(np.where(df.index==5)[0])
# [1]
print(np.where(df['c']==6)[0])
# [1]
返回的值是一个数组,因为在一列中可能有多个具有特定索引或值的行。
发布于 2016-02-02 03:35:48
请改用Index.get_loc。
重用@unutbu的设置代码,您将获得相同的结果。
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
columns = list('abc'),
index=pd.Series([2,5], name='b'))
>>> df
a b c
b
2 1 2 3
5 4 5 6
>>> df.index.get_loc(5)
1
发布于 2018-10-23 23:11:24
使用Index.get_loc和常规条件:
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
columns = list('abc'),
index=pd.Series([2,5], name='b'))
>>> df
a b c
b
2 1 2 3
5 4 5 6
>>> df.index.get_loc(df.index[df['b'] == 5][0])
1
https://stackoverflow.com/questions/18199288
复制相似问题