将第一行与数据框中的列标题合并 [英] Merge the first row with the column headers in a dataframe

查看:73
本文介绍了将第一行与数据框中的列标题合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清理Excel文件以进行进一步的研究.我遇到的问题是,我想合并第一行和第二行.我现在拥有的代码:

I am trying to clean up a Excel file for some further research. Problem that I have, I want to merge the first and second row. The code which I have now:

xl = pd.ExcelFile("nanonose.xls")
df = xl.parse("Sheet1")
df = df.drop('Unnamed: 2', axis=1)
## Tried this line but no luck
##print(df.head().combine_first(df.iloc[[0]]))

此输出为:

      Nanonose     Unnamed: 1     A     B    C          D          E  \
0  Sample type  Concentration   NaN   NaN  NaN        NaN        NaN   
1        Water           9200  95.5  21.0  6.0  11.942308  64.134615   
2        Water           9200  94.5  17.0  5.0   5.484615  63.205769   
3        Water           9200  92.0  16.0  3.0  11.057692  62.586538   
4        Water           4600  53.0   7.5  2.5   3.538462  35.163462   

           F         G         H  
0        NaN       NaN       NaN  
1  21.498560  5.567840  1.174135  
2  19.658560  4.968000  1.883444  
3  19.813120  5.192480  0.564835  
4   6.876207  1.641724  0.144654 

因此,我的目标是合并第一行和第二行以获取:样本类型|浓度A | B | C | D | E | F | G |高

So, my goal is to merge the first and second row to get: Sample type | Concentration | A | B | C | D | E | F | G | H

有人可以帮我合并这两行吗?

Could someone help me merge these two rows?

推荐答案

我认为您需要 numpy.concatenate ,类似cᴏʟᴅsᴘᴇᴇᴅ的原理:

I think you need numpy.concatenate, similar principe like cᴏʟᴅsᴘᴇᴇᴅ answer:

df.columns = np.concatenate([df.iloc[0, :2], df.columns[2:]])
df = df.iloc[1:].reset_index(drop=True)
print (df)
  Sample type Concentration     A     B    C          D          E          F  \
0       Water          9200  95.5  21.0  6.0  11.942308  64.134615  21.498560   
1       Water          9200  94.5  17.0  5.0   5.484615  63.205769  19.658560   
2       Water          9200  92.0  16.0  3.0  11.057692  62.586538  19.813120   
3       Water          4600  53.0   7.5  2.5   3.538462  35.163462   6.876207   

          G         H  
0  5.567840  1.174135  
1  4.968000  1.883444  
2  5.192480  0.564835  
3  1.641724  0.144654  

这篇关于将第一行与数据框中的列标题合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆