0

I have a file named 0.csv, with 15 columns and 100 lines.

I have a different file names 8.csv that has only one column and the same amount of lines 100.

I need to replace a certain column in first file, 0.csv with the column that I get from second file: 8.csv (Columns have same amount of rows).

And then do the same thing with few other columns.

(As I need to solve this in IronPython, I cannot use Pandas).

I'm able to read/write to .csv using Python, I just could not find an example on how to write to a specific column.

Help greatly appreciated!

Thank you!

alc
  • 199
  • 3
  • 15

1 Answers1

0

Python has the zip function which transposes the table (uses columns as rows). There is another SO question related to this

Well the general idea is to have a list for each row

[ col1, col2, col3, ... ]

Then make another list with all those rows

[ [ col1, col2, col3, ... ],
  [ col1, col2, col3, ...] ]

Then with zip(), you should get

x = [ [ col1, col1, col1, ...], 
      [ col2, col2, col2, ...] ]

You can easily change column 8 with

x[8] = new_column

Then retranspose with zip again to bring rows back in columns.

Finally you have to rewrite the csv data back to a (new) file

Community
  • 1
  • 1
Eric
  • 19,525
  • 19
  • 84
  • 147
  • Thanks, but I'm not sure how that will get me where I want to be: replace a specific column (no. 8) in a .csv file, with a column from another .csv file. Second file is made of a single column, with same anount of rows. Probably my knowledge in Python is not to great and your answer is above my knowledge. If you can explain a bit, probably I'll get it. Thanks! – alc Mar 05 '17 at 02:20
  • Thanks. I was actually doing something similar, but not as sophisticated like your: I'm trying to write out all the columns as independent .csv and the combine back into a single .csv. But I'll try yours as well. In any case, I still need to figure out a way to replace a specific column in an existing .csv. Thanks again. – alc Mar 05 '17 at 03:21