converting a list to datafame pandas

Multi tool use
converting a list to datafame pandas
Creating a list in a loop, my final list looks like below:
L [col1, col2, col3, col4
0 N 225.0 12.0 03.0 B ,
col1, col2, col3, col4
0 W 223.0 12.0 01.0 M ,
col1, col2, col3, col4
0 X 203.0 11.0 04.0 P ]
Im trying to convert this to a pandas DataFrame?
Each row looks like a proper dataframe in itself:
L[0]
col1 col2 col3 col4
N 225.0 12.0 03.0 B
2 Answers
2
I believe need create 2d numpy array with DataFrame
contructor:
DataFrame
L = ['col1', 'col2', 'col3', 'col4',
'N 225.0', '12.0', '03.0', 'B' ,
'col1', 'col2', 'col3', 'col4',
'W 223.0', '12.0', '01.0', 'M' ,
'col1', 'col2', 'col3', 'col4',
'X 203.0', '11.0', '04.0', 'P' ]
a = np.array(L).reshape(-1, 8)[:, -4:]
print (a)
[['N 225.0' '12.0' '03.0' 'B']
['W 223.0' '12.0' '01.0' 'M']
['X 203.0' '11.0' '04.0' 'P']]
df = pd.DataFrame(a, columns = L[:4])
print (df)
col1 col2 col3 col4
0 N 225.0 12.0 03.0 B
1 W 223.0 12.0 01.0 M
2 X 203.0 11.0 04.0 P
Explanation:
First convert list to 1d numpy array:
print (np.array(L))
['col1' 'col2' 'col3' 'col4' 'N 225.0' '12.0' '03.0' 'B' 'col1' 'col2'
'col3' 'col4' 'W 223.0' '12.0' '01.0' 'M' 'col1' 'col2' 'col3' 'col4'
'X 203.0' '11.0' '04.0' 'P']
then reshape to Nx8 nd array:
print (np.array(L).reshape(-1, 8))
[['col1' 'col2' 'col3' 'col4' 'N 225.0' '12.0' '03.0' 'B']
['col1' 'col2' 'col3' 'col4' 'W 223.0' '12.0' '01.0' 'M']
['col1' 'col2' 'col3' 'col4' 'X 203.0' '11.0' '04.0' 'P']]
And last select last 4 colums:
print (np.array(L).reshape(-1, 8)[:, -4:])
[['N 225.0' '12.0' '03.0' 'B']
['W 223.0' '12.0' '01.0' 'M']
['X 203.0' '11.0' '04.0' 'P']]
@harold_noobie - Sure, but one thing, my list is same like your? Because
,
and '
are mising in your data.– jezrael
Jul 3 at 5:53
,
'
not working. I get a key error, while converting to array: np.array(L)
– harold_noobie
Jul 3 at 6:02
@harold_noobie - My list
L
is same like your? Or soemthing different?– jezrael
Jul 3 at 6:25
L
My List has index as well, edited the original quest - That is why Im getting Key error while trying the np based solution.
– harold_noobie
Jul 3 at 16:43
Try this
L = ['Thanks You', 'Its fine no problem', 'Are you sure']
#create new df
df = pd.DataFrame({'col':L})
print (df)
There are
col1
, col2
, col3
and col4
in data, so this is not possible use.– jezrael
Jul 3 at 5:40
col1
col2
col3
col4
My list has columns aswell.
– harold_noobie
Jul 3 at 5:41
check the answer given by jezrael that will work
– Amandeep Singh
Jul 3 at 5:43
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
could you explain the solution?
– harold_noobie
Jul 3 at 5:52