在 Pandas 中创建具有自定义索引参数的 DataFrame
pandasserver side programmingprogramming更新于 2025/11/9 18:20:00
要创建具有某些索引的 DataFrame,我们可以传递一个值列表并将它们分配到 DataFrame 类中的索引中。
步骤
创建一个二维、大小可变、可能异构的表格数据 df。
将索引列表放在 DataFrame 类的索引中。
使用自定义索引打印 DataFrame。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:
", df
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
},
index=["John", "Jacob", "Ally", "Simon"]
)
print "With Customized Index:
", df
输出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 With Customized Index: x y z John 5 4 4 Jacob 2 1 1 Ally 1 5 5 Simon 9 10 0

