-1

So I have a csv file that looks like this..

1   a
2   b
3   c

And I want to make it look like this..

1   2   3
a   b   c

I'm at a loss for how to do this with python3, anyone have any ideas? Really appreciate it

Jake
  • 13
  • 4

2 Answers2

1

Are you reading the csv with pandas? you can always use numpy or pandas transpose

import numpy as np
ar1 = np.array([[1,2,3], ['a','b','c']])
ar2 = np.transpose(ar1)

Out[22]: 
array([['1', 'a'],
       ['2', 'b'],
       ['3', 'c']], 
      dtype='<U11')
0

As others have mentioned, pandas and transpose() is the way to go here. Here is an example:

import pandas as pd

input_filename = "path/to/file"

# I am using space as the sep because that is what you have shown in the example
# Also, you need header=None since your file doesn't have a header
df = pd.read_csv(input_filename ), header=None, sep="\s+")  # read into dataframe

output_filename = "path/to/output"
df.transpose().to_csv(output_filename, index=False, header=False)

Explanation:

read_csv() loads the contents of your file into a dataframe which I called df. This is what df looks like:

>>> print(df)

    0   1
0   1   a
1   2   b
2   3   c

You want to switch the rows and columns, and we can do that by calling transpose(). Here is what the transposed dataframe looks like:

>>> print(df.transpose())

   0  1  2
0  1  2  3
1  a  b  c

Now write the transposed dataframe to a file with the to_csv() method. By specifying index=False and header=False, we will avoid writing the header row and the index column.

pault
  • 41,343
  • 15
  • 107
  • 149