用顶行替换标题

问题描述 投票:0回答:14

我目前有一个如下所示的数据框:

       Unnamed: 1    Unnamed: 2   Unnamed: 3  Unnamed: 4
0   Sample Number  Group Number  Sample Name  Group Name
1             1.0           1.0          s_1         g_1
2             2.0           1.0          s_2         g_1
3             3.0           1.0          s_3         g_1
4             4.0           2.0          s_4         g_2

我正在寻找一种方法来删除标题行并使第一行成为新的标题行,因此新的数据框将如下所示:

    Sample Number  Group Number  Sample Name  Group Name
0             1.0           1.0          s_1         g_1
1             2.0           1.0          s_2         g_1
2             3.0           1.0          s_3         g_1
3             4.0           2.0          s_4         g_2

我已经尝试过类似的方法,然后制作没有标题的数据框

if 'Unnamed' in df.columns:

但我似乎没有取得任何进展。

python pandas header row
14个回答
356
投票


106
投票

new_header = df.iloc[0] #grab the first row for the header df = df[1:] #take the data less the header row df.columns = new_header #set the header row as the df header

然后

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

应该可以解决问题。 


76
投票

df.to_csv(path, index=False)



20
投票

df.rename(columns=df.iloc[0]).drop(df.index[0])

这不会重置索引

尽管如此,相反的情况却不会如预期那样工作

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

    


10
投票

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

    


9
投票
df.rename(columns=df.iloc[0], inplace = True) df.drop([0], inplace = True)

设置了

row
索引,所以我们可以通过转置数据框、设置索引并将其转回来对列执行相同的操作: set_index

请注意,如果您的行已经具有不同的索引,则可能需要更改 
df = df.T.set_index(0).T

中的

0
    


7
投票

这个案例我们可以使用,

set_index(0)

读取文件时,这将跳过第一行并将该列设置为文件的第二行。


3
投票

pd.read_csv('file_path',skiprows=1)

我将列表拆分为列表的部分看起来多余,但除此之外,标题仍然作为实际表的一部分出现。


1
投票

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

如果您喜欢它,请点击向上箭头。谢谢


1
投票

df.columns = df.iloc[0] df = df.reindex(df.index.drop(0)).reset_index(drop=True) df.columns.name = None Sample Number Group Number Sample Name Group Name 0 1.0 1.0 s_1 g_1 1 2.0 1.0 s_2 g_1 2 3.0 1.0 s_3 g_1 3 4.0 2.0 s_4 g_2

    


0
投票


0
投票

header = table_df.iloc[0] table_df.drop([0], axis =0, inplace=True) table_df.reset_index(drop=True) table_df.columns = header table_df



0
投票

def promote_df_headers(df): ''' Takes a df and uses the first row as the header Parameters ---------- df : DataFrame Any df with one or more columns. Returns ------- df : DataFrame Input df with the first row removed and used as the column names. ''' new_header = df.iloc[0] df = df[1:] df.columns = new_header df = df.reset_index(drop=True) return df



-4
投票
最佳 OneLiner

pd.read_csv('file_path',header=0)

注意标题值:

标题指的是用作列名称的行号。别搞错了,行号不是 df 而是来自 Excel 文件(0 是第一行,1 是第二行,依此类推)。

这样,您将获得所需的列名称,而无需编写额外的代码或创建新的 df。

好的事情是,它会删除替换的行。

© www.soinside.com 2019 - 2024. All rights reserved.