如何在Pandas中设置第一行为标题(附实例)

2,677 阅读2分钟

你可以使用下面的基本语法来设置pandas DataFrame的第一行作为标题:

df.columns = df.iloc[0]
df = df[1:]

下面的例子展示了如何在实践中使用这种语法。

例子:在Pandas中设置第一行作为页眉

假设我们有如下的pandas DataFrame,其中包含各种篮球运动员的信息:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'Bad Name 1': ['team', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'Bad Name 2': ['points', 18, 22, 19, 14, 14, 11, 20, 28],
                   'Bad Name 3': ['assists', 5, 7, 7, 9, 12, 9, 9, 4],
                   'Bad Name 4': ['rebounds', 11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  Bad Name 1 Bad Name 2 Bad Name 3 Bad Name 4
0       team     points    assists   rebounds
1          A         18          5         11
2          B         22          7          8
3          C         19          7         10
4          D         14          9          6
5          E         14         12          6
6          F         11          9          5
7          G         20          9          9
8          H         28          4         12

假设第一行包含了我们真正想在标题中使用的值。

为了将第一行设置为标题,我们可以使用以下语法:

#set column names equal to values in row index position 0
df.columns = df.iloc[0]

#remove first row from DataFrame
df = df[1:]

#view updated DataFrame
print(df)

0 team points assists rebounds
1    A     18       5       11
2    B     22       7        8
3    C     19       7       10
4    D     14       9        6
5    E     14      12        6
6    F     11       9        5
7    G     20       9        9
8    H     28       4       12

请注意,现在第一行的值被用作标题。

如果你想重置DataFrame的索引,使用下面的代码:

#reset index values
df.reset_index(drop=True, inplace=True)

#view updated DataFrame
print(df)

0 team points assists rebounds
0    A     18       5       11
1    B     22       7        8
2    C     19       7       10
3    D     14       9        6
4    E     14      12        6
5    F     11       9        5
6    G     20       9        9
7    H     28       4       12

现在索引被重置了,所以第一行的索引值为0

其他资源

下面的教程解释了如何在pandas中执行其他常见任务:

如何在Pandas中按名称选择列
如何在Pandas中按索引选择列
如何在Pandas中选择包含特定字符串的列