python - 通过索引符号而不是列名称选择数据框中的列

标签 python pandas

我想使用条目“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来查找起始索引。然后使用 ilocnp._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/

相关文章:

python - Pandas - 计算所有列的 z 分数

python - 如何循环遍历 Pandas Dataframe 中的数字列并过滤值?

python : import module once for a whole package

python - 如何使用 pandas 读取其中项目是引用的文本文件

python - 从python pandas的多个目录中的多个excel文件中提取数据

python - 如何有效地获取唯一值的索引列表?

python - IronPython 和 WPF : Binding a checkbox's IsChecked property to a class member variable

python - 简单游戏的Pygame低帧率

python - 如何在 Django Web 应用程序中存储奇异的动态值?

python - 如何在 Linux 中显示进程状态(阻塞、非阻塞)