Pandas DataFrame 的起始索引为 1 [英] start index at 1 for Pandas DataFrame

查看:124
本文介绍了Pandas DataFrame 的起始索引为 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将 Pandas DataFrame 写入 CSV 时,我需要索引从 1 开始,而不是从 0 开始.

这是一个例子:

In [1]: import pandas as pd在 [2]: result = pd.DataFrame({'Count': [83, 19, 20]})在 [3]: result.to_csv('result.csv', index_label='Event_id')

产生以下输出:

在 [4]: !cat result.csv事件 ID,计数0,831,192,20

但我想要的输出是这样的:

在[5]中:!cat result2.csv事件 ID,计数1,832,193,20

我意识到这可以通过向我的数据框中添加一列移位 1 的整数序列来完成,但我是 Pandas 的新手,我想知道是否存在更简洁的方法.

解决方案

Index是一个对象,默认索引从0开始:

<预><代码>>>>结果索引Int64Index([0, 1, 2], dtype=int64)

你可以用

将这个索引移动1<预><代码>>>>结果.index += 1>>>结果索引Int64Index([1, 2, 3], dtype=int64)

I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV.

Here's an example:

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')                               

Which produces the following output:

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

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.

解决方案

Index is an object, and default index starts from 0:

>>> result.index
Int64Index([0, 1, 2], dtype=int64)

You can shift this index by 1 with

>>> result.index += 1 
>>> result.index
Int64Index([1, 2, 3], dtype=int64)

这篇关于Pandas DataFrame 的起始索引为 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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