如何将列名称从元组更改为字符串? [英] How to change the columns name from a tuple to string?

查看:119
本文介绍了如何将列名称从元组更改为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫数据框中使用了pd.pivot_table,列名变成了像('A1', 'B1'), ('A1', 'B2')...这样的元组,我希望它们像是'A1_B1', 'A1_B2'...

I have used pd.pivot_table in pandas dataframe, and the columns names becomes tuples like ('A1', 'B1'), ('A1', 'B2')... and I want them to be like 'A1_B1', 'A1_B2'...

我尝试使用 df.columns.values[i] = df.columns.values[i][0] + '_' + df6.columns.values[i][1], 并尝试重命名.

I tried to use df.columns.values[i] = df.columns.values[i][0] + '_' + df6.columns.values[i][1], and tried rename as well.

当我检查df.columns.values时,列的名称已更改,但是当我无法使用这些名称进行索引时.我是python的新手,所以可能不知道列名和列索引之间的区别.

When I checked df.columns.values, the columns' names changed, but when I cannot use these names to do indexing. I am new to python, so might not know the difference between column names and column indices.

有人可以帮助我吗?谢谢!

Can anyone help me? Thanks!

推荐答案

设置

setup

df = pd.DataFrame(
    np.arange(8).reshape(2, 4),
    columns=[('A1', 'B1'), ('A2', 'B1'), ('A1', 'B2'), ('A2', 'B2')])

print(df)

   (A1, B1)  (A2, B1)  (A1, B2)  (A2, B2)
0         0         1         2         3
1         4         5         6         7

rename

df.rename(columns='_'.join, inplace=True)
print(df)

   A1_B1  A2_B1  A1_B2  A2_B2
0      0      1      2      3
1      4      5      6      7

map

df.columns = df.columns.map('_'.join)
print(df)

   A1_B1  A2_B1  A1_B2  A2_B2
0      0      1      2      3
1      4      5      6      7

这篇关于如何将列名称从元组更改为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆