📅  最后修改于: 2023-12-03 15:18:13.941000             🧑  作者: Mango
pandas index from 1 - Python
In Python's pandas
library, by default, the indexing of data starts from 0, which means the first element of the data is accessed using index 0. However, sometimes it is more intuitive to have the index start from 1 instead of 0. This guide will demonstrate how to create a pandas DataFrame or Series with index starting from 1 instead of 0 and how to manipulate the index.
To create a DataFrame with index starting from 1, we can use the range()
function and specify the start parameter as 1, and then pass the resulting list as the index
parameter when creating the DataFrame.
import pandas as pd
data = {'col1': [1, 2, 3, 4],
'col2': ['A', 'B', 'C', 'D']}
df = pd.DataFrame(data, index=list(range(1, 5)))
print(df)
Output:
col1 col2
1 1 A
2 2 B
3 3 C
4 4 D
When accessing data with an index starting from 1, you simply use the index values as you would normally. However, remember that internally, pandas still operates with a zero-based index, so the index 1 in the DataFrame corresponds to the zero-based index 0.
print(df.loc[1]) # Accessing row with index 1
# Output:
# col1 1
# col2 A
# Name: 1, dtype: object
print(df['col1'][1]) # Accessing value in column 'col1' at index 1
# Output:
# 1
If you have an existing DataFrame or Series with a 0-based index and you want to change it to start from 1, you can reassign a new index to the DataFrame or Series.
df.index = range(1, len(df) + 1)
print(df)
Output:
col1 col2
1 1 A
2 2 B
3 3 C
4 4 D
Now, the DataFrame df
has been modified to have index values starting from 1.
In this guide, we discussed how to create a pandas DataFrame or Series with an index starting from 1 in Python. We also learned how to access data and modify the index to start from 1. Using these techniques, you can work with data in a way that is more intuitive and aligned with your requirements.