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:
的思路,然后使数据框架没有标题df.to_csv(newformat,header=False,index=False)
,但我似乎没有任何进展。
11 个回答
0 人赞同
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
0 人赞同
数据框架可以通过以下方式进行改变
df.columns = df.iloc[0]
df = df[1:]
df.to_csv(path, index=False)
Should do the trick.
0 人赞同
如果你想要一个单行本,你可以做。
df.rename(columns=df.iloc[0]).drop(df.index[0])
0 人赞同
另一个使用Python交换的单行线。
df, df.columns = df[1:] , df.iloc[0]
This won't reset the index
虽然,反过来也不会有预期的效果df.columns, df = df.iloc[0], df[1:]
。
0 人赞同
@ostrokach的回答是最好的。 最有可能的是,你想在对数据框架的任何引用中保持这一点,因此将从inplace = True中受益。
df.rename(columns=df.iloc[0], inplace = True)
df.drop([0], inplace = True)
0 人赞同
这里有一个简单的技巧,可以 "就地 "定义列索引。因为set_index
设置row我们可以通过转置数据框,设置索引,然后再转回,对列做同样的事情。
df = df.T.set_index(0).T
注意,如果你的行已经有了不同的索引,你可能必须改变0
中的set_index(0)
。
0 人赞同
另外,我们也可以在用pandas读取文件时这样做。
这种情况下,我们可以使用。
pd.read_csv('file_path',skiprows=1)
读取文件时,这将跳过第一行,并将该列设置为文件的第二行。
0 人赞同
--另一种方法是这样做的
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 人赞同
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 人赞同
出于某种原因,我不得不这样做。
df.columns = [*df.iloc[0]]
df = table[1:]
我将列表分割成的部分看起来是多余的,但除此之外,标题仍然作为实际表格的一部分出现。
0 人赞同
最佳做法和Best OneLiner:
df.to_csv(newformat,header=1)