I have the following dict:
td = {'q1':(111,222), 'q2':(333,444)}
I would like to convert it to a dataframe that looks like this:
Query Value1 Value2 q1 111 222 q2 333 444
I have tried the following:
df = pd.DataFrame(td.items())
The result looks like this:
0 1 0 q1 (111,222) 1 q2 (333,444)
If it wasn't entirely obvious, I am new to python and pandas. How can I get a dictionary with values as tuples to behave as separate columns in a dataframe?
My end goal is to display percent difference between value1 and value2.
We can create pandas dataframe by using tuples.
Python Dictionaries Python dictionary is a collection which is unordered, changeable and indexed. Each item of a dictionary has a key:value pair and are written within curly brackets separated by commas. The values can repeat, but the keys must be unique and must be of immutable type(string, number or tuple).
Using Tuples as Keys in Dictionaries. Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we must use a tuple as the key. Write code to create a dictionary called 'd1', and in it give the tuple (1, 'a') a value of “tuple”.
We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method. Example 1: Passing the key value as a list.
Setup
td = {'q1':(111,222), 'q2':(333,444)}
Option 1
pd.DataFrame(td).T.rename_axis('Query').add_prefix('Value').reset_index() Query Value0 Value1 0 q1 111 222 1 q2 333 444
Option 2
from cytoolz.dicttoolz import merge pd.DataFrame( [merge( {'Query': k}, {'Value{}'.format(i): x for i, x in enumerate(v, 1)} ) for k, v in td.items()] ) Query Value1 Value2 0 q1 111 222 1 q2 333 444
Response to Comment
df = pd.DataFrame(td).T.rename_axis('Query').add_prefix('Value') df.assign(PctChg=df.pct_change(axis=1).iloc[:, -1]).reset_index() Query Value0 Value1 PctChg 0 q1 111 222 1.000000 1 q2 333 444 0.333333
Or
df = pd.DataFrame(td).T.rename_axis('Query').add_prefix('Value') df.eval('PctChg = Value1 / Value0 - 1', inplace=False).reset_index() Query Value0 Value1 PctChg 0 q1 111 222 1.000000 1 q2 333 444 0.333333
Try this ?
td = {'q1':(111,222), 'q2':(333,444)} df = pd.DataFrame(td).T df Out[25]: 0 1 q1 111 222 q2 333 444
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With