Skip to main content
 首页 » 编程设计

python之在 Pandas 系列中嵌入一个范围

2024年10月17日8zhoujg

我有一个包含 14 列的表,我想将选定的列拉入一个新的数据框中。 假设我想要第 0 列,然后是第 8-14 列

  dfnow = pd.Series([df.iloc[row_count,0], \ 
                    df.iloc[row_count,8], \ 
                    df.iloc[row_count,9], \ 
                    .... 

工作但看起来笨拙

我想写

  dfnow = pd.Series([df.iloc[row_count,0], \ 
          df.iloc[row_count, range (8, 14)]]) 

但这会抛出一个 ValueError: Wrong number of items passed

现在,从下面的答案中,我知道我可以创建两个单独的 sereis 并将它们连接起来,但这似乎也不太理想。

Adding pandas Series with different indices without getting NaNs

请您参考如下方法:

这是你想要的吗?

In [52]: df = pd.DataFrame(np.arange(30).reshape(5,6), columns=list('abcdef')) 
 
In [53]: df 
Out[53]: 
    a   b   c   d   e   f 
0   0   1   2   3   4   5 
1   6   7   8   9  10  11 
2  12  13  14  15  16  17 
3  18  19  20  21  22  23 
4  24  25  26  27  28  29 
 
In [54]: df[[0,2,4]] 
Out[54]: 
    a   c   e 
0   0   2   4 
1   6   8  10 
2  12  14  16 
3  18  20  22 
4  24  26  28 

将列 0、2、4 连接( reshape )为单个系列:

In [68]: df[[0,2,4]].values.T.reshape(-1,) 
Out[68]: array([ 0,  6, 12, 18, 24,  2,  8, 14, 20, 26,  4, 10, 16, 22, 28]) 
 
In [69]: pd.Series(df[[0,2,4]].values.T.reshape(-1,)) 
Out[69]: 
0      0 
1      6 
2     12 
3     18 
4     24 
5      2 
6      8 
7     14 
8     20 
9     26 
10     4 
11    10 
12    16 
13    22 
14    28 
dtype: int32