Python Forum
Converting list to variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting list to variables
#1
Hi Guys,

I'm really stuck on this one. I was given a file that looks like this.
Output:
id original 0 1 [['U K', 1], ['U S A', 2]] 1 2 [['U K', 2], ['U E A', 1]] 2 3 [] 3 4 [['France', 3]] 4 5 [['U K', 6]]
(the code is just to generate this sample table that matches exactly the format I was given.)
data = {'id':[1, 2, 3, 4, 5], 'original':["[['U K', 1], ['U S A', 2]]", ["['U K', 2], ['U E A', 1]"], [], ["['France', 3]"]
,["['U K', 6]"]]}
df = pd.DataFrame(data)
print (df)
And I am asked to convert the same table to look like this.

Output:
id original U_K U_S_A U_E_A France 0 1 [['U K', 1], ['U S A', 2]] 1 2 1 2 [['U K', 2], ['U E A', 1]] 2 1 2 3 [] 3 4 [['France', 3]] 3 4 5 [['U K', 6]] 6
(again code just to generate the desirable output)
data = {'id':[1, 2, 3, 4, 5], 'original':["[['U K', 1], ['U S A', 2]]", ["['U K', 2], ['U E A', 1]"], [], ["['France', 3]"]
,["['U K', 6]"]], 'U_K':[1,2,"","",6], 'U_S_A':[2,"","","",""],'U_E_A':["",1,"","",""],'France':["","","",3,""]}
df = pd.DataFrame(data)
print (df)
I cannot change the format, It is given. The original file has 200k rows and, after converting, 200 columns... And I am at lost on this one.

Any help will be appreciated, thanks in advance.
Reply
#2
They want a pivot table. pandas.Dataframe has a pivot() method.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Advancing Through Variables In A List knight2000 0 499 May-13-2023, 03:30 AM
Last Post: knight2000
  Converting a list to dictinary tester_V 8 2,637 Jul-02-2021, 09:04 PM
Last Post: tester_V
  Converting tkinter listbox into list BigSwiggy 6 3,526 Feb-07-2021, 02:01 PM
Last Post: BigSwiggy
  Trouble with converting list , dict to int values! faryad13 7 3,667 Sep-04-2020, 06:25 AM
Last Post: faryad13
  Print variable values from a list of variables xnightwingx 3 2,571 Sep-01-2020, 02:56 PM
Last Post: deanhystad
  Using a list of variables Zane217 6 2,478 Jun-09-2020, 01:37 PM
Last Post: Yoriz
  converting list of zero length to a matrix of 3*3 vp1989 2 1,890 May-20-2020, 07:46 PM
Last Post: deanhystad
  add all variables to a list faszination_92 6 3,051 Apr-14-2020, 04:36 AM
Last Post: buran
  converting string object inside a list into an intiger bwdu 4 2,552 Mar-31-2020, 10:36 AM
Last Post: buran
  Creating a List with many variables in a simple way donnertrud 1 2,011 Jan-11-2020, 03:00 PM
Last Post: Clunk_Head

Forum Jump:

User Panel Messages

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