假设我有一个数据框(使用 pandas 数据分析库),如下所示:
Unnamed Column1:
1 'Puppies'
2 6
3 15
4 13
5 12
我想让数据框看起来像这样:
'Puppies'
1 6
2 15
3 13
4 12
5 80
如何向上移动所有内容,包括用于替换列名称的条目。有办法做到这一点吗?
请您参考如下方法:
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
请注意,如果标题行缺少列名称,"Unnamed: 1" 听起来很像 pd.read_csv 分配给该列的名称。在这种情况下,您可以使用 skiprows=1 来解决问题,而不是像上面那样修补结果。或 header=1 代替。 skiprows=1 会导致 pd.read_csv 跳过第一行,从而自动从第二行读取标题(列名)。
