Reputation: 5126
I have the following lists:
l1 = [(1,2),(3,4),(5,6)]
l2 = [7,8,9]
I want the output as df
df =
c1 c2 c3
0 1 2 7
1 3 4 8
2 5 6 9
So far I can separate out just the tuple as
df = pd.DataFrame(l1)
that gives me:
c1 c2
0 1 2
1 3 4
2 5 6
I want to do for multiple lists of different forms as mentioned above.
Upvotes: 2
Views: 63
Reputation: 51335
You could also just use pd.concat
, and concatenate the dataframes resulting from pd.DataFrame(l1)
and pd.Dataframe(l2)
:
df = pd.concat([pd.DataFrame(l1), pd.DataFrame(l2)], axis=1)
>>> df
0 1 0
0 1 2 7
1 3 4 8
2 5 6 9
Upvotes: 2
Reputation: 402553
2-list form:
pd.DataFrame([*x, y] for x, y in zip(l1, l2))
0 1 2
0 1 2 7
1 3 4 8
2 5 6 9
Multi-list form:
from collections import Sequence
lists = [l1, l2, ...]
pd.DataFrame([
[
k for j in i for k in (j
if isinstance(j, Sequence) else [j]
)]
for i in zip(*lists)
])
0 1 2
0 1 2 7
1 3 4 8
2 5 6 9
This will work for any case regardless of whether l_i
is a list of tuples or list of integers.
Upvotes: 4