Last active
August 14, 2023 22:19
-
-
Save jshawl/c8f4723bd3236519787650cb270a4f2e to your computer and use it in GitHub Desktop.
Combine Two CSVs side-by-side
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
# note: << in ruby is the same as .push | |
# [1,2] << 15 #=> [1,2,15] | |
new_csv = [] | |
CSV.foreach('csv1.csv') do |csv1| | |
new_csv << csv1 | |
end | |
line = 0 | |
CSV.foreach('csv2.csv') do |csv2| | |
new_csv[line].push(*csv2) # check out python extend method | |
line = line + 1 | |
end | |
CSV.open('csv_combined.csv','w') do |csv| | |
csv << new_csv.shift # put the headers in the array | |
new_csv.each do |row| | |
csv << row | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one | two | |
---|---|---|
a | b |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
three | four | |
---|---|---|
c | d |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one | two | three | four | |
---|---|---|---|---|
a | b | c | d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@
![image](https://user-images.githubusercontent.com/142224380/260584930-0af4f5c7-8a67-4746-b4f3-39d67f3c3c9a.jpg)