我想使用条目“Start”作为行索引和列索引的引用,从给定的输入 df
创建一个 df_D
。
我不想使用列名A、B、C
等。
相反,我希望使用索引,因为序列始终是“START”的前 3 列和最后 3 列,即类似 n,n+1,n+2, n+5,n +6,n+7
输入:
df = pd.DataFrame({'A':['jfgh',23,'Ndfg',34,0,56],'B':['jfgh',23,'START',34,0,56], 'C':['cvb',7,'dsfgA',65,47,3],'D':['rrb',7,'gfd',3,0,7],'E':['dfg',7,'gfd',5,12,1],'F':['dfg',7,'sdfA',5,0,4],'G':['dfg',7,'sdA',5,8,9],'H':['dfg',7,'gfA',5,0,8],'I':['dfg',7,'sdfA',5,7,23]})
输出:
A B C D E F G H I
0 jfgh jfgh cvb rrb dfg dfg dfg dfg dfg
1 23 23 7 7 7 7 7 7 7
2 Ndfg START dsfgA gfd gfd sdfA sdA gfA sdfA
3 34 34 65 3 5 5 5 5 5
4 0 0 47 0 12 0 8 0 7
5 56 56 3 7 1 4 9 8 23
所需输出:df_D 手动创建
B C D G H I
0 0 47 0 8 0 7
1 56 3 7 9 8 23
尝试1:
for index in range(len(df)):
if str(df.loc[index,'C']).startswith('START'):
df_D = df.iloc[index+1:len(df), [1,2,3,6,7,8]]
break
结果输出:
Empty DataFrame
Columns: [B, C, D, G, H, I]
Index: []
我哪里出错了?
最佳答案
我们可以使用np.where
来查找起始索引。然后使用 iloc
和 np._r
来创建我们的切片:
start_col = np.where(df.eq("START"))[1][0]
cols = df.shape[1]
col_select = np.r_[start_col: start_col+3, cols-3: cols]
df.iloc[-2:, col_select]
B C D G H I
4 0 47 0 8 0 7
5 56 3 7 9 8 23
关于python - 通过索引符号而不是列名称选择数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137132/