lundi 3 juillet 2017

Randomly Shuffle Two CSV Files Independently in Python

Unfortunately, I do not have much experience in programming, but I want to achieve the following with Python (and I would be really happy when someone would help me doing and understanding this):

I have two csv files, say list1.csv and list2.csv and I want to combine them in a new csv after randomly shuffle them seperately in the following way: Suppose list1.csv has the following structure:

Header1 Header2
A       1
B       2
C       3
…       …

I want to shuffle the elements of the two columns (but not the headers), but keep the elements in each row together, e.g.:

Header1 Header2
B       2
A       1
C       3
…       …

For list2.csv I want to do the same thing and it has the very same structure, i.e.:

Header3 Header4
a       x1
b       x2
c       x3
…       …

In the end I want to glue them together in a new, seperate csv (the individual items in the csv's are stimuli for an experiment) with the following result:

Header1 Header2 Header3 Header4
B       2       c       x3
C       3       a       x1
A       1       b       x2
…       …       …       …

I think, I have to do the following (based on what I googled together):

#I actually do not know why I write this :)
import random 

#I guess this activates the import of a csv :)
import csv 

#Import the first csv file and store it in a variable
#I also want to tell Python that I want him to ignore the headers, but later on I need them back somehow :o
list1=list(csv.reader(open('list1.csv', header=None))) 

As you make have noticed I'm very unfamiliar with this :( I guess I need to learn some Python in the future!

From what I read I think I need to extract the rows and glue them together with zip() and then use random.shuffle().

I hope I was clear in what my goals are and I would be really greatful for some help :)




Aucun commentaire:

Enregistrer un commentaire