Reputation: 1
I am trying to merge the strings from the first two rows of a .csv file into one row in python. I am using a file with over 150 columns.
Right now it looks like this:
but I need to merge the information into one row, that looks like this:
Upvotes: 0
Views: 701
Reputation: 1
Ok, I managed to do it by converting the .csv file into an array.
def addheader(inputfile):
results = []
with open(inputfile, "r") as r:
reader = csv.reader(r, delimiter=';')
for row in reader:
i = i+1
if i < x:
results.append(row)
i = 0
x = len(results[0])-1
while i < x:
i = i+1
results[1][i] = results[0][i] + " " + results[1][i]
Upvotes: 0
Reputation: 83
Using the pandas library you can do this,
First of installing the pandas library if you don't have,
By using this command
pip install pandas
Then add this script in your code
import pandas as pd
data=pd.read_csv("YOUR FILE LOCATION WITH FILE NAME")
This line will print you the first row of your excel sheet
print(data.ioc[0])
You can combine the first two rows into one row and save in the first row
data.iloc[0]=[data.iloc['YOUR COLUMN NAME'][0]+data.iloc['YOUR COLUMN NAME'][1],data.iloc[]+.......]
Like this for your every column and it will save in the first row And Run a loop for remaining rows and update it.
For saving from the data variable that is data frame TO CSV
data.to_csv('your-file-name.csv', sep=',')
Upvotes: 1