Pandas append/concat two values from a dictionary object into a data frame

Question:

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)
Asked By: Renee

||

Answers:

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
Answered By: fsimonjetz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.