在 Pandas 中创建具有自定义索引参数的 DataFrame
要创建具有某些索引的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:\n", 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: \n", 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