简体   繁体   中英

How do I extract a list of lists from a Pandas DataFrame?

I have a DataFrame in Pandas:

import numpy as np
import pandas as pd
d = {'Person': ["A", "B", "B", "C"], 'Movies': ["ET", "Apollo 13", "12 Angry Men", "Citizen Kane"]}
df = pd.DataFrame(data=d)
print df

I'd like to extract from this DataFrame a list of lists containing one list for each person, and which contains all the movies that they watched. Something like:

[["ET"], ["Apollo 13", "12 Angry Men"], ["Citizen Kane"]]

This is probably straightforward but I'm struggling with it.

Thanks in advance!

Try:

print(df.groupby("Person").agg(list)["Movies"].to_list())

Prints:

[['ET'], ['Apollo 13', '12 Angry Men'], ['Citizen Kane']]

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