私は次のデータフレームを持っています:
a b c
b
2 1 2 3
5 4 5 6
ご覧のとおり、列b
はインデックスとして使用されます。('b' == 5)
この場合、 を満たす行の序数を取得したいと思います1
。
テストされる列は、インデックス列 (b
この場合のように) または通常の列のいずれかです。たとえば、満たす行のインデックスを見つけたい場合があります('c' == 6)
。
代わりに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]
列に特定のインデックスまたは値を持つ複数の行が存在する可能性があるため、返される値は配列です。
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