【发布时间】:2015-07-20 19:28:38
【问题描述】:
我有一个管道文本文件,其结构如下所示:
seatle|washington|13|35|1|NW|2005-05-10
sanfransisco|california|13|31|1|W|2005-05-10
chicago|illinois|10|33|1|C|2005-05-10
newyorkcity|newyork|9|32|2|E|2005-05-10
DC|DC|9|30|4|E|2005-05-10
miami|florida|9|20|4|SE|2005-05-10
dallas|texas|12|22|2|S|2005-05-10
在上面的示例中,5th 列是一个类别编号。数据集中可以有n 的类别数量(在上面的示例中有3 类别-1、2 和4,但数量可能会有所不同)。现在我想要从input file 读取数据,根据column 5 中的类别旋转column 3 和4,并创建另一个output file,其结构应如下所示:
column 1|column 2|column 6|column 7|column3_catgory1|column3_catgory2|column3_catgory3|....|column4_catgory1|column4_catgory2|column4_catgory3|...
因此输出文件应该有来自输入文件column 1,column 2,column 6,column 7的数据,然后是column 3的数据,基于column 5的值在相应的输出列中提到接下来是基于column 5的值在相应输出列中提到的column 4的数据。因此对于上述示例输入,输出文件应如下所示:
column 1 |column 2 |column 6|column 7 |column3_1|column3_2|column3_4|column4_1|column4_2|column4_4
seatle |washington|NW |2005-05-10|13 | | |35 | |
sanfransisco|california|W |2005-05-10|13 | | |31 | |
chicago |illinois |C |2005-05-10|10 | | |33 | |
newyorkcity |newyork |E |2005-05-10| |9 | | |32 |
DC |DC |E |2005-05-10| | |9 | | |30
如您所见,由于存在3 类别,因此输入的column 3 和4 被转为输出中的三个不同列,并根据类别在相应列中提及值。例如,对于带有seatle 的行,因为类别是1,所以column 3 和column 4 的值分别在column3_1 和column4_1 中与其他第3 列类别值(column3_2 & column3_4) 和第 4 列类别值 (column4_2 & column4_4) 为空。
现在这是我编写的用于读取管道文件并确定有多少类别的代码,但我无法在此之前继续。
category = []
read = open('file1.txt', 'r')
for line in read:
fields = line.split('|')
if fields[4] not in category:
category.append(fields[4])
category = map(int, category) #converts the category value to int for sorting
category.sort()
谁能帮助我如何在这之前进行并适当地调整价值观?
注意:即使输入文件中没有header,我想在输出文件中添加标题,就像我在上面的示例输出结构中显示的那样。同样在输出中,我不希望两列值之间有任何额外的空格,正如我在示例输入的示例输出数据中所示。我特意添加了这些空格,以便更轻松地查看我想要的内容。
【问题讨论】:
-
我会查看
pandas。您可以使用pandas.read_tables将输出文件加载到pandas.DataFrame,传递sep='|'。有很多选项可用于处理标题等。然后应该很容易拆分数据帧、添加列等。另外,请查看 pandas.pydata.org/pandas-docs/stable/merging.html ,您也许可以使用 @987654359 完成您想要做的事情@ 功能。你可能会花很多时间来编写自己的数据库代码,但如果你打算在 python 中做严肃的数据库工作,请使用 pandas -
@dermen 它不是数据库工作。输入是一个文件,输出也是一个文件。我想要的只是根据输入文件中的
column 5值将输入数据的column 3和column 4旋转到输出中的不同列 -
我明白了。尽管如此,您正在使用列、行样式数据,为此,
pandas有一些方便的工具,我将发布一个示例。