0

I am using Python 2.7 on Windows7. I just learned Python for 2 days and got some CSV modules unfamiliar, hope to obtain your help here.

My current output(CSV data) is like this:

Angle Dist Intensity Error
0      0    32896   8080
1      0    32896   8080
2      0    32896   8080
3      0    32896   8080
4      0    32896   8080
5      0    32896   8080
6      0    32896   8080
7      0    32896   8080

My question is, how to transpose/rearrange data from columns to one row in Python? To be more specific, I would like to get the following format:

Angle 1 2 3 4...7 Dist 0 0 0...0 Intensity # # # # ... Error # # # # ...

My current code is:

with open("C:\Logging\\" + date + "Result.csv", 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        csv.writer(f, row)
martineau
  • 119,623
  • 25
  • 170
  • 301
Amber.G
  • 1,343
  • 5
  • 12
  • 16
  • 1
    There are many questions on SO that deal around the same issue. One such question can be found at http://stackoverflow.com/questions/16503560/read-specific-columns-from-a-csv-file-with-csv-module. In your case, you would be selecting all columns instead of specific columns. Hope it helps – Malik May 18 '17 at 00:33
  • What are your delimiters, because they are clearly not commas. tabs or spaces? – Paul Rooney May 18 '17 at 00:34
  • hi @PaulRooney the delimiters are commas. The output is like: A,B,C,D (first row) x1,y1,m1,n1 (second row) x2,y2,m2,n2 (third row) – Amber.G May 18 '17 at 00:36
  • Thanks @PedroLobito I tried out the link, but got an error on 'print(y+'\t', end='')' as 'invalid snytax'. Besides, his code is just 'print' to python but my case is print to CSV file in one row. So I think i need to search around more~~~ – Amber.G May 18 '17 at 00:51
  • @Amber.G: The answer to the duplicate question is written in Python 3, For Python 2 use `print y+'\t',` —note the trailing comma. – martineau May 18 '17 at 02:20
  • @Amber.G: If you want all the data to become one row of a csv file, instead of printing it you will need to concatenate the results of all the items returned from the `zip()` call and write that to a new csv file. You can do the latter by creating a `csv.writer` instance from a new file opened for writing (`mode='wb'`). – martineau May 18 '17 at 02:27

1 Answers1

1

If pandas is not too much of an overkill for you, the following snippet should do the trick:

import pandas as pd

df = pd.read_csv(filename)
df.values.flatten()
Daniel
  • 11,332
  • 9
  • 44
  • 72
  • it looks like i have trouble installing Pandas: I followed installation step by step until the last step 'pip install pandas' and got 'requirement already satisfied' (I went through the steps twice to double-confirm...). But when use Panda in my python, I got an error 'No module named pandas'... – Amber.G May 18 '17 at 01:44