簡體   English   中英

從 pandas dataframe 獲取值列表

[英]Get a list of values from a pandas dataframe

我有一個像這樣的 DataFrame

df.head()
>>>
Date Region   Manager   SalesMan    Item         Units  Unit_price  Sale_amt
 0   East     Martha    Alexander   Television   ...      ...         ...
 1   Central  Hermann   Shelli      Home Theater ...      ...         ...
 2   Central  Hermann   Luis        Television   ...      ...         ...
 3   Central  Timothy   David       CellPhone    ...      ...         ...
 4   West     Timothy   Stephen     Television   ...      ...         ...

這是獨特的經理和銷售人員

df['Manager'].unique()
array(['Martha', 'Hermann', 'Timothy', 'Douglas'], dtype=object)


df['SalesMan'].unique()
array(['Alexander', 'Shelli', 'Luis', 'David', 'Stephen', 'Steven',
       'Michael', 'Sigal', 'Diana', 'Karen', 'John'], dtype=object)

我想要一個 dataframe,其中包含唯一經理和這些經理下的唯一銷售人員列表例如,對於上述 dataframe,我想要一個 output,例如:

Manager     list_of_salesmen
Martha      [ALexander]
Herman      [Shelli, Luis]
Timothy     [David, Stephen]

我想使用 groupby 並在那里被擊中? 我該如何解決這個問題?

您可以在 Manager 上使用groupby.agg ,並將list傳遞給 SalesMan:

>>> df.groupby('Manager').agg({'SalesMan':list})

                SalesMan
Manager                  
Hermann    [Shelli, Luis]
Martha        [Alexander]
Timothy  [David, Stephen]

It can be done by making a dict() object that contains data for new dataset and use pandas.DataFrame.from_dict() to convert it to dataframe:

d = {'Manager':list(df['Manager'].unique()), 'SalesMan':[]}

for i in df['Manager'].unique():
    d['SalesMan'].append([i for i in df[df['Manager'] == i]['SalesMan']])

df2 = pd.DataFrame.from_dict(d)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM