简体   繁体   中英

Convert list of lists to a dataframe in python

I have the following lists:

sample  location    date    spiceis sp.ab
1   001 9/10/2017   sp1 2
1   001 9/10/2017   sp2 5
1   001 9/10/2017   sp3 10
1   001 9/10/2017   sp4 2
2   002 9/11/2017   sp1 0
2   002 9/11/2017   sp2 2
2   002 9/11/2017   sp3 5
2   002 9/11/2017   sp4 5
3   003 9/12/2017   sp1 2
3   003 9/12/2017   sp2 1
3   003 9/12/2017   sp3 1
3   003 9/12/2017   sp4 0
4   004 9/13/2017   sp1 7
4   004 9/13/2017   sp2 4
4   004 9/13/2017   sp3 2
4   004 9/13/2017   sp4 9

And i would like to return a dataframe that looks like the following. Can anyone help me with this?

sample  location    date    sp1 sp2 sp3 sp4
1   001 9/10/2017   2   5   10  2
2   002 9/11/2017   0   2   5   5
3   003 9/12/2017   2   1   1   0
4   004 9/13/2017   7   4   2   9

Assuming each row is a list and by dataframes you mean Pandas dataframes, then you can use list comprehensions to turn the list of lists into a list of tuples:

listoftuples = [tuple(l) for l in listoflists]

Then use the from_records function:

import pandas as pd
df = pd.DataFrame.from_records(listoftuples,columns=['sample','location','date','spiceis','sp.ab'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM