使单元格条目成为pandas数据框中列的名称

use*_*835 1 python excel numpy scipy pandas

假设我有一个数据框(使用pandas数据分析库),如下所示:

   Unnamed Column1:
1  'Puppies'
2  6
3  15
4  13
5  12
Run Code Online (Sandbox Code Playgroud)

我希望数据框看起来像这样:

   'Puppies'
1  6
2  15
3  13
4  12
5  80
Run Code Online (Sandbox Code Playgroud)

如何改变一切,包括替换列名称的条目.有没有办法做到这一点?

unu*_*tbu 6

df.columns = df.iloc[0]   # set the columns to the values in the first row
df = df.iloc[1:]          # reassign df to all rows but the first
Run Code Online (Sandbox Code Playgroud)

请注意,如果标题行缺少列名,则"Unnamed: 1"声音会像名称一样pd.read_csv分配给列.在这种情况下,您可以使用skiprows=1header=1替代修复问题,而不是修补上面显示的结果.skiprows=1会导致pd.read_csv跳过第一行,从而自动从第二行读取标题(列名).