Pandas DataFrame的起始索引从1开始 [英] start index at 1 for Pandas DataFrame
本文介绍了Pandas DataFrame的起始索引从1开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将Pandas DataFrame写入CSV时,我需要索引从1开始而不是0.
I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV.
这是一个例子:
In [1]: import pandas as pd
In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})
In [3]: result.to_csv('result.csv', index_label='Event_id')
哪个会产生以下输出:
In [4]: !cat result.csv
Event_id,Count
0,83
1,19
2,20
但是我想要的输出是这样:
But my desired output is this:
In [5]: !cat result2.csv
Event_id,Count
1,83
2,19
3,20
我意识到这可以通过向数据帧中添加一列以1为单位的整数序列来完成,但是我是Pandas的新手,我想知道是否存在更干净的方法.
I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and I'm wondering if a cleaner way exists.
推荐答案
索引是一个对象,默认索引从0
开始:
Index is an object, and default index starts from 0
:
>>> result.index
Int64Index([0, 1, 2], dtype=int64)
您可以使用
>>> result.index += 1
>>> result.index
Int64Index([1, 2, 3], dtype=int64)
这篇关于Pandas DataFrame的起始索引从1开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文