Convert list to dataframe (Pandas)
Question:
Is there any way I can convert this type of output into a Dataframe? Output:
[['A', 'B'], ['Orange', 'Apple']]
[['C', 'D'], ['Coconut', 'Lemon']]
[['E'], ['Mango', 'Strawberry']]
I want to turn the output into a dataframe like this:
` x1 X2
0 A,B Orange, Apple
1 C,D Coconut, Lemon
2 E Mango, Strawberry`
Answers:
Just add this data to a list
import pandas as pd
data = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame(data, columns=['x1', 'x2'])
so df looks like
x1 x2
0 [A, B] [Orange, Apple]
1 [C, D] [Coconut, Lemon]
2 [E] [Mango, Strawberry]
Simple fix:
pd.DataFrame(
{"x1":[["A", "B"], ["C", "D"], ["E"]],
"x2":[["Orange", "Apple"], ["Coconut", "Lemon"], ["Mango", "Strawberry"]]}
)
If your starting data is in a list, and you would like to join each list with a comma, this should work:
l = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame([[', '.join(v) for v in i] for i in l],columns = ['x1','x2'])
Also stack()
with str.join()
is an option:
df = pd.DataFrame(l,columns = ['x1','x2']).stack().str.join(', ').unstack()
or
df = pd.DataFrame(l).applymap(', '.join).rename(lambda x: 'x{}'.format(x+1),axis=1)
Output:
x1 x2
0 A, B Orange, Apple
1 C, D Coconut, Lemon
2 E Mango, Strawberry
Is there any way I can convert this type of output into a Dataframe? Output:
[['A', 'B'], ['Orange', 'Apple']]
[['C', 'D'], ['Coconut', 'Lemon']]
[['E'], ['Mango', 'Strawberry']]
I want to turn the output into a dataframe like this:
` x1 X2
0 A,B Orange, Apple
1 C,D Coconut, Lemon
2 E Mango, Strawberry`
Just add this data to a list
import pandas as pd
data = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame(data, columns=['x1', 'x2'])
so df looks like
x1 x2
0 [A, B] [Orange, Apple]
1 [C, D] [Coconut, Lemon]
2 [E] [Mango, Strawberry]
Simple fix:
pd.DataFrame(
{"x1":[["A", "B"], ["C", "D"], ["E"]],
"x2":[["Orange", "Apple"], ["Coconut", "Lemon"], ["Mango", "Strawberry"]]}
)
If your starting data is in a list, and you would like to join each list with a comma, this should work:
l = [[['A', 'B'], ['Orange', 'Apple']],
[['C', 'D'], ['Coconut', 'Lemon']],
[['E'], ['Mango', 'Strawberry']]]
df = pd.DataFrame([[', '.join(v) for v in i] for i in l],columns = ['x1','x2'])
Also stack()
with str.join()
is an option:
df = pd.DataFrame(l,columns = ['x1','x2']).stack().str.join(', ').unstack()
or
df = pd.DataFrame(l).applymap(', '.join).rename(lambda x: 'x{}'.format(x+1),axis=1)
Output:
x1 x2
0 A, B Orange, Apple
1 C, D Coconut, Lemon
2 E Mango, Strawberry