2015-11-06 96 views
7

我有一个csv文件,其中有几列,我首先用冒号(;)分隔。但是,ONE列由管道分隔我想分隔这个列并创建新的列。分隔一个特定的列并将它们添加为CSV(Python3,CSV)的列

输入:

Column 1 Column 2  Column 3 
    1   2   3|4|5 
    6   7   6|7|8 
    10   11   12|13|14 

所需的输出:

Column 1 Column 2  ID Age Height 
    1   2   3  4 5 
    6   7   6  7 8 
    10   11   12  13 14 

到目前为止我的代码限定在第一时间通过;然后转换为DF(这是我期望的最终格式)

delimit = list(csv.reader(open('test.csv', 'rt'), delimiter=';')) 
df = pd.DataFrame(delimit) 
+1

可以解析最后一栏和[分割它(http://stackoverflow.com/questions/14745022/pandas-dataframe-how-do- –

回答

3

你并没有完全显示的数据是什么样子(你说它是由分号分隔,但你的例子没有任何),但如果它看起来像

Column 1;Column 2;Column 3 
1;2;3|4|5 
6;7;6|7|8 
10;11;12|13|14 

你可以做somethi NG像

>>> df = pd.read_csv("test.csv", sep="[;|]", engine='python', skiprows=1, 
        names=["Column 1", "Column 2", "ID", "Age", "Height"]) 
>>> df 
    Column 1 Column 2 ID Age Height 
0   1   2 3 4  5 
1   6   7 6 7  8 
2  10  11 12 13  14 

这是通过使用正则表达式分离,意思是“无论是;|”,并手动强制列名。

或者,你能做到这一点的几个步骤:

>>> df = pd.read_csv("test.csv", sep=";") 
>>> df 
    Column 1 Column 2 Column 3 
0   1   2  3|4|5 
1   6   7  6|7|8 
2  10  11 12|13|14 
>>> c3 = df.pop("Column 3").str.split("|", expand=True) 
>>> c3.columns = ["ID", "Age", "Height"] 
>>> df.join(c3) 
    Column 1 Column 2 ID Age Height 
0   1   2 3 4  5 
1   6   7 6 7  8 
2  10  11 12 13  14 
+0

尝试运行代码的后半部分时出现以下错误:TypeError:split()得到了意外的关键字参数'expand' – user3682157

+1

@ user3682157:您很可能使用老版本的熊猫。 – DSM

0
delimit = list(csv.reader(open('test.csv', 'rt'), delimiter=';')) 

for row in delimit: 
    piped = row.pop() 
    row.extend(piped.split('|')) 

df = pd.DataFrame(delimit) 

delimit最终看起来像:

[ 
    ['1', '2', '3', '4', '5'], 
    ['6', '7', '6', '7', '8'], 
    ['10', '11', '12', '13', '14'], 
] 
0

它实际上是更快使用CSV lib和str.replace:

import csv 
with open("test.txt") as f: 
    next(f) 
    # itertools.imap python2 
    df = pd.DataFrame.from_records(csv.reader(map(lambda x: x.rstrip().replace("|", ";"), f), delimiter=";"), 
            columns=["Column 1", "Column 2", "ID", "Age", "Height"]).astype(int) 

一些计时:

In [35]: %%timeit 
pd.read_csv("test.txt", sep="[;|]", engine='python', skiprows=1, 
        names=["Column 1", "Column 2", "ID", "Age", "Height"]) 
    ....: 
100 loops, best of 3: 14.7 ms per loop 

In [36]: %%timeit                
with open("test.txt") as f: 
    next(f) 
    df = pd.DataFrame.from_records(csv.reader(map(lambda x: x.rstrip().replace("|", ";"), f),delimiter=";"), 
           columns=["Column 1", "Column 2", "ID", "Age", "Height"]).astype(int) 
    ....: 
100 loops, best of 3: 6.05 ms per loop 

你可以str.split:

with open("test.txt") as f: 
    next(f) 
    df = pd.DataFrame.from_records(map(lambda x: x.rstrip().replace("|", ";").split(";"), f), 
            columns=["Column 1", "Column 2", "ID", "Age", "Height"]) 
0

想出了一个解决方案,我自己:

df = pd.DataFrame(delimit) 
s = df['Column 3'].apply(lambda x: pd.Series(x.split('|'))) 
frame = pd.DataFrame(s) 
frame.rename(columns={0: 'ID',1:'Height',2:'Age'}, inplace=True) 
result = pd.concat([df, frame], axis=1)