fillo
fillo

Reputation: 425

Creating a dataframe from a dict where keys are tuples and values are lists

Assuming that, we have the following dictionary, with keys as tuples and values as lists:

dict_temp  = {('first', 'line'): [1, 2], ('second', 'line'): [1, 21, 11]}

I'd like to create a dataframe with 2+n columns: Col1 and Col2 from tuples, and Col3, Col4, ... from each element in lists which should look like this:

    0       1       2   3   4
0   first   line    1   2   NaN
1   second  line    1   21  11.0

Hence, I need to split the column with lists as well. What I have done is:

dict_temp  = {('first', 'line'): [1, 2], ('second', 'line'): [1, 21, 11]}
df_left    = pd.Series(dict_temp).reset_index()
df_right   = pd.DataFrame(df_left[0].tolist())
df_left    = df_left.drop([0], axis=1) # Drop column
df         = pd.concat([df_left, df_right], axis=1)
#df.columns = [0, 1, 2, 3, 4]
df

The output is:

level_0 level_1     0   1   2
0   first   line    1   2   NaN
1   second  line    1   21  11.0

Although I have handled the issue inspiring by this question and that question, I think there should be a much better pythonic way to cope with it.

Upvotes: 3

Views: 270

Answers (1)

U13-Forward
U13-Forward

Reputation: 71570

Try using this list comprehension with list unpacking, then just simply convert it to a DataFrame:

lst = [[*k] + v for k, v in dict_temp.items()]
print(pd.DataFrame(lst))

Output:

        0     1  2   3     4
0   first  line  1   2   NaN
1  second  line  1  21  11.0

Upvotes: 2

Related Questions