通过连接Pandas中的行来实现Dataframe标头

时间:2021-09-01 15:24:42

Given this example dataframe in 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']})

looking like

       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

I would like to build a new by concatenating e.g. rows 2 & 3 to get something like

我想通过连接例如建立一个新的第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

Any idea for a vector-like realization?

有没有像矢量一样的想法?

Thanks a lot, Sascha

非常感谢,Sascha

1 个解决方案

#1


2  

You can get desired result applying str.join along axis to a dataframe slice. See for example

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

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

If you want to name your columns this way, just do

如果您想以这种方式命名列,只需这样做

>>> 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]

#1


2  

You can get desired result applying str.join along axis to a dataframe slice. See for example

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

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

If you want to name your columns this way, just do

如果您想以这种方式命名列,只需这样做

>>> 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]