Skip to content Skip to sidebar Skip to footer

Manipulating Data Of A Dataframe In Pandas

I'm reading a dataframe and converting it into a json file. I'm using python 3 and 0.25.3 version of pandas for it. I already got some help from you guys (Manipulating data of Pand

Solution 1:

1st Question:

You can write custom function for rename, e.g. like:

def f(x):
    vals = ['part_number', 'number_client']
    if x in vals:
        return x
    else:
        return x.split('_')[0]

2nd Question

If I understand correctly keys in final json are created from columns of original Dataframe, and also by parameter name by reset_index of my solution. If want some another logic for change keys (columns names) is possible change first solution.

3rd Question

In original solution is changed to_json to to_dict for possible modify final list of dict like append text info, for json is used json.dumps in last step:

import json

def f(x):
    vals = ['part_number', 'number_client']
    if x in vals:
        return x
    else:
        return x.split('_')[0]

d =(data.groupby(["id","label","id_customer","label_customer"])['part_number','number_client']
        .apply(lambda x: x.rename(columns=f).to_dict('r')).reset_index(name='Number')
        .groupby(["id", "label"])[ "id_customer", "label_customer", "Number"]
        .apply(lambda x: x.rename(columns=f).to_dict('r')).reset_index(name='Customer')
        .to_dict(orient='records'))

#print (d)

d1 = (data[['Additional_information']].rename(columns={'Additional_information':'text'})
                                      .to_dict(orient='records'))
d1 = {'Additional_information':d1}
print (d1)
{'Additional_information': [{'text': 'testing'}, {'text': 'testing again'}]}

d.append(d1)
#print (d)

j = json.dumps(d)
#print (j)

Post a Comment for "Manipulating Data Of A Dataframe In Pandas"