0

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

1 Answer 1

1

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'])
Sign up to request clarification or add additional context in comments.

3 Comments

i now have found out that my data was not a list of lists; it was a data frame. when i applied the code, an error occurs: AssertionError: 5 columns passed, passed data had 8 columns do you have a modified code for that? thank you very much.
Ah, I think I misunderstood your question. It seems like you should use pivot_table pandas.pydata.org/pandas-docs/stable/generated/…
That's link work for me now. Thank you very much Brine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.