简体   繁体   中英

Creating dataframe from another dataframe and list

I have a list of names like this

names= [Josh,Jon,Adam,Barsa,Fekse,Bravo,Talyo,Zidane]

and i have a dataframe like this

    Number  Names  
0   1       Josh   
1   2       Jon    
2   3       Adam   
3   4       Barsa  
4   5       Fekse  
5   6       Barsa  
6   7       Barsa 
7   8       Talyo  
8   9       Jon  
9   10      Zidane

i want to create a dataframe that will have all the names in names list and the corresponding numbers from this dataframe grouped, for the names that does not have corresponding numbers there should be an asterisk like below

Names Number
Josh  1
Jon   2,9
Adam  3
Barsa 4,6,7
Fekse 5
Bravo *
Talyo 8
Zidane 10

Do we have any built in functions to get this done

You can use GroupBy with str.join , then reindex with your names list:

res = df.groupby('Names')['Number'].apply(lambda x: ','.join(map(str, x))).to_frame()\
        .reindex(names).fillna('*').reset_index()

print(res)

    Names Number
0    Josh      1
1     Jon    2,9
2    Adam      3
3   Barsa  4,6,7
4   Fekse      5
5   Bravo      *
6   Talyo      8
7  Zidane     10

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