pandas将某一列变为索引_python – 在Pandas中将列连接为索引

如果你的列由字符串组成,你可以只使用运算符(在字符串的上下文中添加它们是在

python中连接它们,pandas遵循这个):

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'year':['2012','2012'],'month':['01','02']})

In [3]: df

Out[3]:

month year

0 01 2012

1 02 2012

In [4]: df['concatenated'] = df['year'] + df['month']

In [5]: df

Out[5]:

month year concatenated

0 01 2012 201201

1 02 2012 201202

然后,如果创建了此列,则可以使用set_index来更改索引

In [6]: df = df.set_index('concatenated')

In [7]: df

Out[7]:

month year

concatenated

201201 01 2012

201202 02 2012

请注意,pd.concat不是为了连接字符串而是连接系列/数据帧,因此要将不同数据帧或系列的列或行一起添加到一个数据帧中(而不是将几行/列添加到一行/列中).有关详细说明,请参见http://pandas.pydata.org/pandas-docs/dev/merging.html.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值