[英]How to turn selected headers of a CSV file into a Pandas data frame
我有以下CSV數據
id,gene,celltype,stem,stem,stem,bcell,bcell,tcell
id,gene,organs,bm,bm,fl,pt,pt,bm
id,gene,organs,stem1,stem2,stem3,b1,b2,t1
134,foo,about_foo,20,10,11,23,22,79
222,bar,about_bar,17,13,55,12,13,88
前三行是標題。 我要選擇的是第1行和第3行,然后將其轉換為如下所示的數據框:
Coln1 Coln2
stem stem1
stem stem2
stem stem3
bcell b1
bcell b2
tcell t1
我堅持以下幾點:
import pandas as pd
df = pd.read_csv("http://dpaste.com/00AWDBW.txt",header=None,index_col=[1,2]).iloc[:, 1:]
您可以使用參數nrows
和skiprows
在read_csv
:
import pandas as pd
import io
temp=u"""id,gene,celltype,stem,stem,stem,bcell,bcell,tcell
id,gene,organs,bm,bm,fl,pt,pt,bm
id,gene,organs,stem1,stem2,stem3,b1,b2,t1
134,foo,about_foo,20,10,11,23,22,79
222,bar,about_bar,17,13,55,12,13,88"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),header=None,index_col=[1,2], nrows=2, skiprows=[1])
df = df.ix[:, 1:].reset_index(drop=True).T
df.columns = ['Coln1', 'Coln2']
print df.reset_index(drop=True)
Coln1 Coln2
0 stem stem1
1 stem stem2
2 stem stem3
3 bcell b1
4 bcell b2
5 tell t1
要將前3個標題選擇為列,請執行以下操作:
df = pd.read_csv(io.StringIO(temp),header=None,index_col=[1,2], nrows=3, skiprows=[4])
df = df.ix[:, 1:].reset_index(drop=True).T
df.columns = ['Coln1', 'Coln2','Coln3']
print df.reset_index(drop=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.