You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas读取CSV时将首列异常为0的索引恢复正常

Fixing the Continuous Index When Reading CSV with pandas

Absolutely, there are a couple of straightforward ways to restore the expected continuous index (0, 1, 2, ...) when reading your CSV file with pandas. Let's break down the options based on your scenario:

Option 1: Replace the invalid first column after reading

If you want to keep the structure of your CSV intact but overwrite the all-zero first column with a proper continuous index, this is the simplest approach:

import pandas as pd

# Read the CSV (add `header=None` if your file has no column headers)
df = pd.read_csv("your_file.csv", header=None)

# Replace the first column (index 0) with a sequence of continuous integers
df.iloc[:, 0] = range(len(df))

This works because range(len(df)) generates exactly the 0-starting continuous sequence you need, perfectly matching the number of rows in your DataFrame.

Option 2: Ignore the invalid first column during reading

If the all-zero first column serves no purpose other than being a broken index, you can skip it entirely and let pandas automatically create a proper continuous index for you:

import pandas as pd

# First, get the total number of columns to define which ones to keep
temp_df = pd.read_csv("your_file.csv", header=None)
total_columns = temp_df.shape[1]

# Read only columns 1 to end; pandas will auto-generate an index starting at 0
df = pd.read_csv("your_file.csv", header=None, usecols=range(1, total_columns))

If your CSV has column headers, you can skip the first column by name (replace 'broken_index' with your actual first column name):

df = pd.read_csv("your_file.csv", usecols=lambda col: col != 'broken_index')

Option 3: Set a new index and discard the invalid column

Another alternative is to read the file normally, then replace the broken index with a clean one and remove the useless first column:

import pandas as pd

df = pd.read_csv("your_file.csv", header=None)
# Create a new continuous index and drop the original all-zero column
df = df.set_index(pd.Index(range(len(df)))).drop(df.columns[0], axis=1)

This is ideal if you don't need to retain the first column's position in your DataFrame at all.

All these methods will give you the clean, continuous index you expect. Pick the one that best fits whether you need to keep the first column's spot or discard it entirely.

内容的提问来源于stack exchange,提问作者Василий Масов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:29:49