栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何更改pandas数据框索引值?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何更改pandas数据框索引值?

使用此设置:

import pandas as pdimport iotext = '''STK_ID RPT_Date sales cash000568 20120930 80.093 57.488000596 20120930 32.585 26.177000799 20120930 14.784 8.157'''df = pd.read_csv(io.BytesIO(text), delimiter = ' ',       converters = {0:str})df.set_index(['STK_ID','RPT_Date'], inplace = True)

df.index
可以
MultiIndex
像这样将索引重新分配给新的索引:

index = df.indexnames = index.namesindex = [('000999','20121231')] + df.index.tolist()[1:]df.index = pd.MultiIndex.from_tuples(index, names = names)print(df)#        sales    cash# STK_ID RPT_Date     # 000999 20121231  80.093  57.488# 000596 20120930  32.585  26.177# 000799 20120930  14.784   8.157

或者,可以将索引划分为列,然后可以重新分配列中的值,然后将列返回索引:

df.reset_index(inplace = True)df.ix[0, ['STK_ID', 'RPT_Date']] = ('000999','20121231')df = df.set_index(['STK_ID','RPT_Date'])print(df)#        sales    cash# STK_ID RPT_Date     # 000999 20121231  80.093  57.488# 000596 20120930  32.585  26.177# 000799 20120930  14.784   8.157

使用IPython进行基准测试

%timeit
建议,重新分配索引(上面的第一种方法)比重置索引,修改列值然后再次设置索引(上面的第二种方法)要快得多:

In [2]: %timeit reassign_index(df)10000 loops, best of 3: 158 us per loopIn [3]: %timeit reassign_columns(df)1000 loops, best of 3: 843 us per loop


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号