在 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