假设我有以下pd数据帧
df = pd.DataFrame(np.random.randint(0, 10, size=(20, 3)), columns=list('ABC'))
>>> df
A B C
0 7 4 7
1 4 8 7
2 8 8 3
3 4 8 0
4 9 4 3
5 5 6 1
6 9 1 6
7 6 0 5
8 4 3 9
9 1 0 5
10 6 2 1
11 2 2 7
12 7 9 1
13 3 5 5
14 0 9 1
15 5 5 3
16 0 1 3
17 6 1 1
18 1 4 7
19 4 8 0
我想创建一个新列D,它基于df的索引保存一些特定的值,即使该索引不是特别存在,而是将所有索引设置在特定范围内。到目前为止,我的尝试似乎无济于事
df.loc[0:5, "D"] = "one"
df.loc[5:10, "D"] = "two"
df.loc[10:, "D"] = "three"
基本上,我想得到一个看起来像这样的df
A B C D
0 7 4 7 one
1 4 8 7 one
2 8 8 3 one
3 4 8 0 one
4 9 4 3 one
5 5 6 1 two
6 9 1 6 two
7 6 0 5 two
8 4 3 9 two
9 1 0 5 two
10 6 2 1 two
11 2 2 7 three
12 7 9 1 three
13 3 5 5 three
14 0 9 1 three
15 5 5 3 three
16 0 1 3 three
17 6 1 1 three
18 1 4 7 three
19 4 8 0 three
如何实现?