Python Forum
How to covert row values into columns values?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to covert row values into columns values?
#9
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.


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
>>>
"""
Reply


Messages In This Thread
RE: How to covert row values into columns values? - by Pedroski55 - Aug-06-2021, 10:14 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  remove duplicates from dicts with list values wardancer84 27 877 May-27-2024, 04:54 PM
Last Post: wardancer84
Question Using Lists as Dictionary Values bfallert 8 610 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  Printing out incidence values for Class Object SquderDragon 3 434 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 485 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  Too much values to unpack actualpy 3 584 Feb-11-2024, 05:38 PM
Last Post: deanhystad
  Converting column of values into muliple columns of counts highland44 0 330 Feb-01-2024, 12:48 AM
Last Post: highland44
  __init__() got multiple values for argument 'schema' dawid294 4 2,993 Jan-03-2024, 09:42 AM
Last Post: buran
  How to access values returned from inquirer cspower 6 1,014 Dec-26-2023, 09:34 PM
Last Post: cspower
  partial functions before knowing the values mikisDeWitte 4 715 Dec-24-2023, 10:00 AM
Last Post: perfringo
  need to compare 2 values in a nested dictionary jss 2 973 Nov-30-2023, 03:17 PM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020