Pandas - 如何在追加到DataFrame时控制列顺序

2 投票
1 回答
6360 浏览
提问于 2025-04-20 02:46

我正在努力弄明白如何把一个有N行的DataFrame,和两个各有N行的Series合并在一起。现在我做的事情(错的地方)是:

print df['Survived'].shape               # Series should be 1st column
print pd.Series(kmeans.labels_).shape    # Series should be 2nd column
print pd.DataFrame(X_pca).shape          # DataFrame should be remaining columns
new_df = pd.DataFrame()
new_df['Survived'] = df['Survived']
new_df['ClusterId'] = pd.Series(kmeans.labels_)
new_df = new_df.append(pd.DataFrame(X_pca))
print new_df.shape
print new_df.columns.values

而输出结果是:

(1309,)
(1309,)
(1309, 9)
(2618, 11)
[0L 1L 2L 3L 4L 5L 6L 7L 8L 'ClusterId' 'Survived']

我有两个地方不太明白:

  1. 列的顺序完全不对。我试过先从DataFrame开始,然后添加'ClusterId'这个Series,最后再加上'Survived'这个Series,但结果的DataFrame列顺序还是和之前一样。
  2. 在用DataFrame.append添加数据后,结果的DataFrame行数翻了一倍。

我试着看文档,但真的很难找到正好覆盖我想做的事情的内容(奇怪的是,这似乎并不是个不寻常的操作)。我还尝试了pd.concat([Series, Series, DataFrame], axis=1),但这报了个错:pandas.core.index.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

1 个回答

3

没有测试数据来调试pandas是非常困难的,但这里有一个我认为接近你步骤的工作示例。

import pandas as pd
import numpy as np

df = pd.DataFrame(dict(a=np.random.randn(5), b=np.random.randn(5),
                       c=np.random.randn(5)))
s1 = df['b']*2
s1.name = 's1'
s2 = df['b']/4
s2.name = 's2'

new_df = pd.concat([s1, s2, df[['a','c']]], axis=1)

这会产生

         s1        s2         a         c
0 -2.483036 -0.310379  1.152942 -1.835202
1 -1.631460 -0.203932  1.299443  0.524964
2  1.264577  0.158072 -0.324786 -0.006474
3 -0.547588 -0.068449 -0.754534 -0.002423
4  0.649246  0.081156  0.003643 -0.375290

如果还有其他问题,试着看看你所做的和这里的最小示例有什么不同。

编辑: 下面是一个说明为什么索引很重要的例子:

In [64]: s1
Out[64]: 
0   -2.483036
1   -1.631460
2    1.264577
3   -0.547588
4    0.649246
Name: s1, dtype: float64

In [65]: s2
Out[65]: 
1   -0.310379
2   -0.203932
3    0.158072
4   -0.068449
5    0.263546
dtype: float64

In [66]: print(pd.concat([s1, s2], axis=1))
          0         1
0 -2.483036       NaN
1 -1.631460 -0.310379
2  1.264577 -0.203932
3 -0.547588  0.158072
4  0.649246 -0.068449
5       NaN  0.263546

撰写回答