Int64Index([ 1, 2, 3, 4, 5], dtype='int64', length=5)
となっているのであれば、df_users.loc[2]
で取得できると思います。
df_users.loc[user_id]
で Key Error となるということは、df_users.index
の中に user_id
が存在しないことを意味します。
サンプルコード
python
1import pandas as pd
2
3
4df = pd.DataFrame(
5 [
6 [101, 201, 301],
7 [102, 202, 302],
8 [103, 203, 303],
9 [104, 204, 304],
10 [105, 205, 305],
11 ],
12 index=[1, 2, 3, 4, 5],
13 columns=[1, 2, 3]
14)
15print(df)
16# 1 2 3
17# 1 101 201 301
18# 2 102 202 302
19# 3 103 203 303
20# 4 104 204 304
21# 5 105 205 305
22
23print(df.index)
24# Int64Index([1, 2, 3, 4, 5], dtype='int64')
25
26# 1行だけ Series として取得したい場合
27print(df.loc[2])
28# 1行分DataFrame として取得したい場合
29print(df.loc[2:2])
30# 0 1 2
31# 2 102 202 302
追記
考えられる可能性として、index
という列名が DataFrame のインデックスになっていない可能性があります。その場合、set_index() でインデックスに設定できます。
python
1import pandas as pd
2
3
4df = pd.DataFrame(
5 [
6 [1, 101, 201, 301],
7 [2, 102, 202, 302],
8 [3, 103, 203, 303],
9 [4, 104, 204, 304],
10 [5, 105, 205, 305],
11 ],
12 columns=["index", 1, 2, 3]
13)
14print(df)
15# index 1 2 3
16# 0 1 101 201 301
17# 1 2 102 202 302
18# 2 3 103 203 303
19# 3 4 104 204 304
20# 4 5 105 205 305
21
22df = df.set_index("index")
23print(df.loc[2])