1

I'm trying to convert my dataframe from this:

import pandas as pd
test = pd.DataFrame({'apples':['red','green','yellow'], 'quantity':
[1,2,3],'tasteFactor':['yum','yum','yuck']})

   apples  quantity tasteFactor
0     red         1         yum
1   green         2         yum
2  yellow         3        yuck

To this format, which is combining keys with values in each row into a new column:

   apples  quantity tasteFactor  combined
0     red         1         yum  ['apples':'red','quantity':'1','tastefactor':'yum']
1   green         2         yum  ['apples':'green','quantity':'2','tastefactor':'yum']
2  yellow         3        yuck  ['apples':'yellow','quantity':'3','tastefactor':'yuck']

I tried to turn the dataframe into a dictionary per row - but that didn't work. The resulting new column doesn't need to be an actual list type. It could be a string.

EDIT 1: Some people have marked this as duplicate and pointed it to creating a dictionary. BUT it's NOT a dictionary - I need the square brackets within the 'combined' column - so it appears like a list.

sweetnlow
  • 85
  • 1
  • 7
  • Have you tried `test['combined'] = test.to_dict(orient='records')` it looks like what you want. – umutto Aug 14 '17 at 08:56
  • Yes I have! But it gives a dictionary. The column needs to read with square brackets (and not the curly braces that a dictionary provides) as the system the data is being imported into requires a specific format. I also tried outputting it as a dictionary, changing it to a string and then replacing the braces with brackets but that solution gave me more problems. It had u' and escape characters placed everwhere... – sweetnlow Aug 14 '17 at 10:55
  • I don't think there is a structure that contains key value pairs in a square brackets. It looks like you need to look deeper into that specific format your system requires. And `u'` character means its unicode, you see it on the console, doesn't matter for the input. – umutto Aug 15 '17 at 01:17

0 Answers0