Reputation: 2769
Say, I have a dictionary of form:
dct = {'A': [1,2,3], 'B': [4,5,6,7]}
How can it be transformed into pandas dataframe such the result will be of the form:
Column1 Column2
A 1
A 2
A 3
B 4
B 5
B 6
B 7
Upvotes: 1
Views: 980
Reputation: 330063
from itertools import chain
pd.DataFrame(list(chain.from_iterable(
((k, v) for v in vals) for (k, vals) in dct.items())),
columns=('Column1', 'Column2'))
Upvotes: 0
Reputation: 316
You can use DataFrame.from_dict
to import the data:
In [1059]: dct = {'A': [1,2,3], 'B': [4,5,6]}
In [1060]: df = pnd.DataFrame.from_dict(dct)
In [1061]: df
Out[1061]:
A B
0 1 4
1 2 5
2 3 6
And then simply use pandas' very handymelt
function to unpivot the dataframe:
In [1062]: pnd.melt(df)
Out[1062]:
variable value
0 A 1
1 A 2
2 A 3
3 B 4
4 B 5
5 B 6
Upvotes: 1