0

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:

  1. ;; Test1; Test1; Test1; Test 2; Test 2; Test2
  2. Name;Birthday; Points Q1; Points Q2; Points Q3; Points Q1; Points Q2; Points Q3

but I need to merge the information into one row, that looks like this:

  1. Name;Birthday;Test1 PointsQ1; Test1 Points Q2; Test1 Points Q3; Test2 Points Q1;...

2 Answers 2

1

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=',')
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.