更改 pandas 数据框索引值?
问题说明
我有一个df
:
>>> df
sales cash
STK_ID RPT_Date
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
并且想要将第一行的索引值从('000568','20120930')
更改为('000999','20121231')
.最终结果将是:
And want to change first row's index value from ('000568','20120930')
to ('000999','20121231')
. Final result will be:
>>> 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
如何实现?
正确答案
使用此设置:
import pandas as pd
import io
text = '''\
STK_ID RPT_Date sales cash
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 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
:
The index, df.index
can be reassigned to a new MultiIndex
like this:
index = df.index
names = index.names
index = [('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
或者,可以将索引划分为列,然后可以重新分配列中的值,然后将列返回索引:
Or, the index could be made into columns, the values in the columns could be then reassigned, and then the columns returned to indices:
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
进行基准测试建议,重新分配索引(上面的第一种方法)比重置索引,修改列值然后再次设置索引(上面的第二种方法)要快得多:
Benchmarking with IPython %timeit
suggests reassigning the index (the first method, above) is significantly faster than resetting the index, modifying column values, and then setting the index again (the second method, above):
In [2]: %timeit reassign_index(df)
10000 loops, best of 3: 158 us per loop
In [3]: %timeit reassign_columns(df)
1000 loops, best of 3: 843 us per loop
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgahck
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20