I'm new into python and pandas and I'm having hard time transforming this 2d list into four independent columns, I'm getting two columns with more than one data for every record. May be I created it the wrong way? I don't know.
Please help me out, I'm trying to make results look like this: These are the columns that I'm looking for
THANK YOU VERY MUCH!!
CodePudding user response:
import pandas as pd
results = [[('three', 'beer'), ('zero', 'wine')], [('one', 'beer'), ('two', 'wine')]]
Player1Qty = []
Player1type = []
Player2Qty = []
Player2type = []
for tmp in results:
Player1Qty.append(tmp[0][0])
Player1type.append(tmp[0][1])
Player2Qty.append(tmp[1][0])
Player2type.append(tmp[1][1])
pd.DataFrame({'Player1Qty': Player1Qty, 'Player1type': Player1type, 'Player2Qty': Player2Qty, 'Player2type': Player2type})
CodePudding user response:
try this:
import numpy as np
import pandas as pd
data = [
[('one', 'apple'), ('three', 'orange') ],
[('two', 'pear'), ('four', 'banana') ]
]
df = pd.DataFrame(data)
out = out = pd.DataFrame([*df.apply(np.hstack, axis=1)])
cols = [f'Player{i//2 1}{"Qty" if i % 2 else "type"}' for i in out.columns]
out.columns = cols
print(out)
>>>
Player1type Player1Qty Player2type Player2Qty
0 one apple three orange
1 two pear four banana