Aug-06-2021, 10:14 AM
It is summer holiday.
Normally, I would be in Spain, in a beautiful mountain village, reading the paper in the square, having a coffee, later a beer, later a
walk to the top of the mountain.
But I'm stuck in China because of the virus!
So I took a look at pandas. Here is one way to solve your problem in pandas.
Normally, I would be in Spain, in a beautiful mountain village, reading the paper in the square, having a coffee, later a beer, later a
walk to the top of the mountain.
But I'm stuck in China because of the virus!
So I took a look at pandas. Here is one way to solve your problem in pandas.
import pandas as pd # open the file csv_file = '/home/pedro/myPython/pandas/transpose_me.csv' df = pd.read_csv(csv_file) """ >>> df col1 col2 0 a 1 1 a 2 2 b 3 3 b 4 4 c 5 5 c 6 >>> """ # get column 1 as a list mylist = df['col1'].tolist() # get rid of the duplicates myset = set(mylist) """ >>> myset {'a', 'c', 'b'} """ # change back to list mylist = list(myset) mylist.sort() # make an empty dictionary mydict = {mylist[i]:[] for i in range(len(mylist))} # if there were more values in the row, need to change this # then we would need another loop to go across the row # len(df.columns) will tell you how many columns # but if all the rows are different, well some values will just be NaN for i in range(df.index.size): key = df.iat[i,0] if key in mylist: value = df.iat[i,1] mydict[key].append(value) # make a new DataFrame df2 = pd.DataFrame(mydict) """ >>> df2 a b c 0 1 3 5 1 2 4 6 """ # done df3 = df2.T """ >>> df3 0 1 a 1 2 b 3 4 c 5 6 >>> """