I have a python code that convert 2D list into pandas dataframe. Where the result is a dataframe with 2 records.
What i expect is to make all the data in one single row where each value is in a different column.
How can i make this happen ?
import pandas as pd
a = [[1,2],[3,5,6]]
print(type(a))
for b in a:
for j in b:
print(j)
dt=zip(a)
df=pd.DataFrame(dt,columns=["d"])
print(type(df))
print(df)
CodePudding user response:
Probably isn't the most efficient way but the following code:
a = [[1,2],[3,5,6]]
one_d_list = [x for b in a for x in b]
df = pd.DataFrame(one_d_list, index= ['a', 'b', 'c', 'd', 'e'])
df.transpose()
will return the following dataframe:
a b c d e
0 1 2 3 5 6
EDIT following question in comments:
b = [[1,2,3,4,5,1,4,7,8,9]]
b_1 = b[0][:5]
b_2 = b[0][5:]
pd.DataFrame([b_1, b_2], columns=['a', 'b', 'c', 'd', 'e'])
Returns:
a b c d e
0 1 2 3 4 5
1 1 4 7 8 9