我目前有一个如下所示的数据框:
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:
但我似乎没有取得任何进展。
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:]
应该可以解决问题。
df.to_csv(path, index=False)
df.rename(columns=df.iloc[0]).drop(df.index[0])
这不会重置索引
尽管如此,相反的情况却不会如预期那样工作
df, df.columns = df[1:] , df.iloc[0]
df.columns, df = df.iloc[0], df[1:]
df.rename(columns=df.iloc[0], inplace = True)
df.drop([0], inplace = True)
设置了
row索引,所以我们可以通过转置数据框、设置索引并将其转回来对列执行相同的操作:
set_index
请注意,如果您的行已经具有不同的索引,则可能需要更改
df = df.T.set_index(0).T
中的
0
。这个案例我们可以使用,
set_index(0)
读取文件时,这将跳过第一行并将该列设置为文件的第二行。
pd.read_csv('file_path',skiprows=1)
我将列表拆分为列表的部分看起来多余,但除此之外,标题仍然作为实际表的一部分出现。
df.columns = [*df.iloc[0]]
df = table[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
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
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
:
pd.read_csv('file_path',header=0)
注意标题值:
标题指的是用作列名称的行号。别搞错了,行号不是 df 而是来自 Excel 文件(0 是第一行,1 是第二行,依此类推)。
这样,您将获得所需的列名称,而无需编写额外的代码或创建新的 df。
好的事情是,它会删除替换的行。