在 Pandas 中,可以使用 df.reset_index() 方法来重置索引。这将为 DataFrame 创建一个新的整数索引,并将原来的索引作为新的一列添加到 DataFrame 中。

下面是一个示例,展示了如何在新建 DataFrame 时引用其他列,并重置索引:

import pandas as pd

# 创建一个包含两列的 DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [10, 20, 30, 40, 50]}

df = pd.DataFrame(data)

# 使用 df['A'] 作为索引创建新的 DataFrame
new_df = pd.DataFrame(df['A'])

# 重置索引
new_df = new_df.reset_index()

print(new_df)

输出结果如下:

   index  A
0      0  1
1      1  2
2      2  3
3      3  4
4      4  5

在上面的示例中,我们创建了一个新的 DataFrame new_df,其中只包含原始 DataFrame df 的列 'A'。然后,我们使用 reset_index() 方法重置了索引,并将原来的索引添加为新的一列。

Pandas 创建 DataFrame 并重置索引:使用现有列作为新索引

原文地址: http://www.cveoy.top/t/topic/fR5q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录