给定 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/