Pandas DataFrame 重置索引:使用 reset_index() 函数
要给一个 DataFrame 重排索引,可以使用 reset_index() 函数。以下是一个示例:
import pandas as pd
# 创建一个 DataFrame
data = {'Name': ['Tom', 'Nick', 'John', 'Alice'],
'Age': [20, 25, 30, 35],
'City': ['London', 'New York', 'Paris', 'Tokyo']}
df = pd.DataFrame(data)
# 重排索引
df = df.reset_index()
print(df)
输出结果如下:
index Name Age City
0 0 Tom 20 London
1 1 Nick 25 New York
2 2 John 30 Paris
3 3 Alice 35 Tokyo
在这个示例中,reset_index() 函数将原始索引重置为一个新的整数索引,并将原始索引作为新的一列添加到 DataFrame 中。
原文地址: https://www.cveoy.top/t/topic/d4lU 著作权归作者所有。请勿转载和采集!