简体   繁体   中英

How to copy one row in a .csv file to another row with python

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;...

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=',')

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM