如何 select Data Frame 中的所有数据?

How to select all data from Data Frame?

我想 select 数据框中的所有数据(索引、列索引和最右边的列除外 - 见下图)并将其存储到一个系列中。这可能很明显,但我无法使任何工作正常进行。例如,我尝试过 a = nai_data.ix[0:19],但它 returns 又是一个包含所有索引的新数据框,我只需要一系列数据。所以我尝试了 a = pd.Series(nai_data.ix[0:19]) 但也没有帮助。我相信一定有一种简单的方法可以做到这一点,但无法找到。任何帮助表示赞赏

也许你在找stack(),可以认为是把列索引移动到行索引中:

In [12]: np.random.seed(2015)

In [13]: df = pd.DataFrame(np.random.randint(10, size=(3,4)))

In [14]: df
Out[14]: 
   0  1  2  3
0  2  2  9  6
1  8  5  7  8
2  0  6  7  8

In [15]: df.stack()
Out[15]: 
0  0    2
   1    2
   2    9
   3    6
1  0    8
   1    5
   2    7
   3    8
2  0    0
   1    6
   2    7
   3    8
dtype: int64

如果您不想要 MultiIndex,请调用 reset_index():

In [16]: df.stack().reset_index(drop=True)
Out[16]: 
0     2
1     2
2     9
3     6
4     8
5     5
6     7
7     8
8     0
9     6
10    7
11    8
dtype: int64

要 select 除了最后一列,您可以使用 df.iloc:

In [17]: df.iloc[:, :-1]
Out[17]: 
   0  1  2
0  2  2  9
1  8  5  7
2  0  6  7

In [18]: df.iloc[:, :-1].stack()
Out[18]: 
0  0    2
   1    2
   2    9
1  0    8
   1    5
   2    7
2  0    0
   1    6
   2    7
dtype: int64

另一种方法是切片并展平底层 NumPy 数组:

In [21]: df.values
Out[21]: 
array([[2, 2, 9, 6],
       [8, 5, 7, 8],
       [0, 6, 7, 8]])

In [22]: df.values[:, :-1]
Out[22]: 
array([[2, 2, 9],
       [8, 5, 7],
       [0, 6, 7]])

In [23]: df.values[:, :-1].ravel()
Out[23]: array([2, 2, 9, 8, 5, 7, 0, 6, 7])

然后使用这些数据构建系列:

In [24]: pd.Series(df.values[:, :-1].ravel())
Out[24]: 
0    2
1    2
2    9
3    8
4    5
5    7
6    0
7    6
8    7
dtype: int64