【发布时间】:2013-08-14 11:46:17
【问题描述】:
我有以下数据框:
a b c
b
2 1 2 3
5 4 5 6
如您所见,b 列用作索引。我想获得满足('b' == 5) 的行的序号,在本例中为1。
被测试的列可以是索引列(在这种情况下与 b 一样)或常规列,例如我可能想找到满足('c' == 6) 的行的索引。
【问题讨论】:
我有以下数据框:
a b c
b
2 1 2 3
5 4 5 6
如您所见,b 列用作索引。我想获得满足('b' == 5) 的行的序号,在本例中为1。
被测试的列可以是索引列(在这种情况下与 b 一样)或常规列,例如我可能想找到满足('c' == 6) 的行的索引。
【问题讨论】:
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
【讨论】:
请改用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
【讨论】:
你可以像这样使用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]
返回的值是一个数组,因为在一列中可能有多行具有特定索引或值。
【讨论】:
np.where(df.index == 5)[0] 不同,pandas 有一个get_loc 功能,看起来更干净。 pandas.pydata.org/pandas-docs/stable/generated/…