0

I am trying to combine a set of two values from a dictionary object into a data frame column I am replacing. This is what my fruits column data frame looks like:

Fruits
------
{'type': 'Apples - Green', 'storeNum': '123456', 'kind': 'Granny Smith'}
{'type': 'Banana', 'storeNum': '246810', 'kind': 'Organic'}
{'type': 'Orange', 'storeNum': '36912', 'kind': 'Cuties - Small'}

What I would like is this:

Fruits
------
Apples - Green | Granny Smith
Banana | Organic
Orange | Cuties - Small

I have this so far but I only get the types. Is there anyway I can combine the 'type' and 'kind' together and replace that df? I have this code so far:

def funct(df):
    fruits_list = []
    for i in range(len(df['Fruits'])):
        fruits_list.append(list(df['Fruits'][i].values())[0])
    df['Fruits'] = fruits_list
    return df

dataframe = funct(df)
Renee
  • 90
  • 2
  • 10
  • 1
    If you change the line with `fruits_list.append...` to `fruits_list.append(f'{list(df["Fruits"][i].values())[0]} | {list(df["Fruits"][i].values())[2]}')`, does it work now? Using double quotes inside the f-string. – Aeronautix Aug 10 '22 at 21:00
  • I'm getting an `SyntaxError: invalid syntax` – Renee Aug 10 '22 at 21:07
  • Oh, I got it. I replaced the single quote with the double quote. Thank you so much! – Renee Aug 10 '22 at 21:10
  • Note to current/future readers that there is a [post on how to loop through a dataframe and why you shouldn't](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758). – Aeronautix Aug 10 '22 at 21:36

1 Answers1

1

You can concatenate string columns with +.

data = [{'type': 'Apples - Green', 'storeNum': '123456', 'kind': 'Granny Smith'},
        {'type': 'Banana', 'storeNum': '246810', 'kind': 'Organic'},
        {'type': 'Orange', 'storeNum': '36912', 'kind': 'Cuties - Small'}]

df = pd.DataFrame({"Fruits": data})

fruits = pd.DataFrame.from_records(df.Fruits)
print(fruits.type + " | " + fruits.kind)

Returns

0    Apples - Green | Granny Smith
1                 Banana | Organic
2          Orange | Cuties - Small
dtype: object

To assign it to the dataframe, you need to do

df['Fruits'] = fruits.type + " | " + fruits.kind
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21