分隔特定列并将其添加为CSV格式的列(Python3,CSV)

时间:2015-11-06 23:22:40

标签: python csv python-3.x pandas

我有一个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(这是我想要的结束格式)<​​/ p>

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

4 个答案:

答案 0 :(得分:3)

你没有准确显示数据的样子(你说它用分号分隔,但你的例子没有),但如果它看起来像

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

您可以执行类似

的操作
>>> 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

这可以通过使用正则表达式分隔符来表示&#34; ;|&#34;并手动强制列名称。

或者,您可以通过几个步骤完成此操作:

>>> 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

答案 1 :(得分: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'],
]

答案 2 :(得分: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"])

答案 3 :(得分: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)