Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict with values as tuples to pandas DataFrame

Tags:

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.

like image 206
ifthenifthen Avatar asked Sep 06 '17 14:09

ifthenifthen


People also ask

Can we create pandas DataFrame using dictionary of tuples?

We can create pandas dataframe by using tuples.

Can a Python dictionary value be a tuple?

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).

Can dictionary have tuple values?

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”.

Can Python dict can be data in pandas?

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.


2 Answers

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 
like image 143
piRSquared Avatar answered Oct 11 '22 11:10

piRSquared


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 
like image 42
BENY Avatar answered Oct 11 '22 10:10

BENY