python - Pandas - 附加到 DataFrame 时如何控制列顺序

标签 python pandas

我很难弄清楚如何获取一个包含 N 行的 DataFrame、一个包含 N 行的系列、另一个包含 N 行的系列,并将它们连接在一起。这是我正在做的(错误):

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”系列,最后附加“Survived”系列,但生成的 DataFrame 的列顺序完全相同。
  2. 使用 DataFrame.append 附加数据帧后,生成的数据帧的行数增加了一倍

我尝试阅读文档,但我很难找到任何涵盖我想要做的事情的内容(奇怪的是,这似乎并不是一件不寻常的事情)。我也尝试过pd.concat([Series, Series, DataFrame], axis=1)但这会引发错误:pandas.core.index.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

最佳答案

在没有测试数据的情况下调试 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

关于python - Pandas - 附加到 DataFrame 时如何控制列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694893/

相关文章:

python - 如何映射或排序两个不同数据帧的值?

python - 按行/列对标签进行排序

python-3.x - Pandas - 用于设置值的 reindex 与 loc 的行为/问题

python - 如何连接字典中文本的连续单词?

python - matplotlib colorbar 小刻度颜色和小刻度数量

python - Beautiful Soup 跳过评论和脚本标签

python - 根据现有 2534 列中的中值在数据框中创建 2534 个新列

python - 将参数发送到 Python 脚本的规范方法是什么?

python - 在新的 Python 版本上安装 Python 模块

python - 根据并行列中的匹配值对数据帧行进行排序