python - 通过连接 Pandas 中的行的数据帧 header

标签 python pandas

给定 Pandas 中的这个示例数据框

df2 = pd.DataFrame({'a' : ['one', 'two', 'three', 'four', 'five', 'six', 'seven'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu']})

看起来像

       a  b    c
0    one  x  abc
1    two  y  def
2  three  y  ghi
3   four  x  jkl
4   five  y  mno
5    six  x  pqr
6  seven  x  stu

我想通过连接例如第 2 行和第 3 行得到类似的东西

   two_three y_y def_ghi
0    one     x   abc
1    two     y   def
2  three     y   ghi
3   four     x   jkl
4   five     y   mno
5    six     x   pqr
6  seven     x   stu

有类似矢量实现的想法吗?

非常感谢,萨沙

最佳答案

您可以沿轴将 str.join 应用于数据帧切片,从而获得所需的结果。参见示例

>>> df.iloc[[1,2]].apply('_'.join, axis=0)
two_three    two_three
y_y                y_y
def_ghi        def_ghi
dtype: object

如果你想用这种方式命名你的列,就这样做

>>> df.columns = df.iloc[[1,2]].apply('_'.join, axis=0)
>>> df
  two_three y_y def_ghi
0       one   x     abc
1       two   y     def
2     three   y     ghi
3      four   x     jkl
4      five   y     mno
5       six   x     pqr
6     seven   x     stu

[7 rows x 3 columns]

关于python - 通过连接 Pandas 中的行的数据帧 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21161775/

相关文章:

python - 如何绘制 Pandas 数据框的多列

python - 为什么 numpy 的 where 操作比 apply 函数快?

Python:如何在遍历列表时只保留所有先前子列表中的元素?

python - 以相反顺序应用 Python Pandas 指数加权平均值

python - Pandas - 你可以在跳过行的同时有条件地回填另一列吗?

python - 根据选定的窗口进行数据帧聚合

pandas - 根据 pandas 中的 groupby 或循环条件划分列

python - Openshift MySQL Cartridge 未重新启动

Python:没有名为 core.exceptions 的模块

python - 如何将 __iter__ 添加到动态类型?