从多个列表读取到Pandas Dataframe中

时间:2016-03-22 14:55:22

标签: python pandas dataframe

我有一个输入文件,其中包含如下数据:

[ABCD,color,NORMAL,N,2015-02-20,1]
[XYZA,color,NORMAL,N,2015-05-04,1]
[GFFD,color,NORMAL,N,2015-07-03,1]
[NAAS,color,NORMAL,N,2015-08-26,1]
[LOWW,color,NORMAL,N,2015-09-26,1]
[KARA,color,NORMAL,N,2015-11-08,1]
[ALEQ,color,NORMAL,N,2015-12-04,1]
[VDDE,color,NORMAL,N,2015-12-23,1]
[QWER,color,NORMAL,N,2016-01-18,1]
[KDSS,color,NORMAL,Y,2015-08-29,1]

我创建了一个变量,用于存储列名称table_columns。如何将其转换为Pandas Dataframe?

应该与从多个列表中读取非常相似,但它将从中读取的列表数量为n。

2 个答案:

答案 0 :(得分:2)

您可以使用read_csvstrip来尝试to_datetime

import pandas as pd
import io

temp=u"""[ABCD,color,NORMAL,N,2015-02-20,1]
[XYZA,color,NORMAL,N,2015-05-04,1]
[GFFD,color,NORMAL,N,2015-07-03,1]
[NAAS,color,NORMAL,N,2015-08-26,1]
[LOWW,color,NORMAL,N,2015-09-26,1]
[KARA,color,NORMAL,N,2015-11-08,1]
[ALEQ,color,NORMAL,N,2015-12-04,1]
[VDDE,color,NORMAL,N,2015-12-23,1]
[QWER,color,NORMAL,N,2016-01-18,1]
[KDSS,color,NORMAL,Y,2015-08-29,1]"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),header=None,names=['a','b','c','d','e','f'])

#remove []
df['a'] = df['a'].str.strip('[')
df['f'] = df['f'].str.strip(']')
#convert column e to datetime
df['e'] = pd.to_datetime(df['e'])
print df
      a      b       c  d          e  f
0  ABCD  color  NORMAL  N 2015-02-20  1
1  XYZA  color  NORMAL  N 2015-05-04  1
2  GFFD  color  NORMAL  N 2015-07-03  1
3  NAAS  color  NORMAL  N 2015-08-26  1
4  LOWW  color  NORMAL  N 2015-09-26  1
5  KARA  color  NORMAL  N 2015-11-08  1
6  ALEQ  color  NORMAL  N 2015-12-04  1
7  VDDE  color  NORMAL  N 2015-12-23  1
8  QWER  color  NORMAL  N 2016-01-18  1
9  KDSS  color  NORMAL  Y 2015-08-29  1

答案 1 :(得分:1)

一种方法是:

from StringIO import StringIO

import pandas as pd

>>> pd.read_csv(StringIO(open('stuff.txt').read().replace('[', '').replace(']', '')), header=None)
    D   color   NORMAL  N   2015-02-20  1
0   XYZA    color   NORMAL  N   2015-05-04  1
1   GFFD    color   NORMAL  N   2015-07-03  1
2   NAAS    color   NORMAL  N   2015-08-26  1
3   LOWW    color   NORMAL  N   2015-09-26  1
4   KARA    color   NORMAL  N   2015-11-08  1
5   ALEQ    color   NORMAL  N   2015-12-04  1
6   VDDE    color   NORMAL  N   2015-12-23  1
7   QWER    color   NORMAL  N   2016-01-18  1
8   KDSS    color   NORMAL  Y   2015-08-29  1