Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

python - How to rearrange the columns of a DataFrame into an indexed binary matrix?

I am trying to convert this dataframe:

data_in = {
    'dates': [2017, 2017, 2018, 2019, 2019, 2019],
    'names': ['Roger', 'Rafa', 'Roger', 'Rafa', 'Novak', 'Dom']
}
df_in = pd.DataFrame(data_in)
>>> df_in
    dates   names
0   2017    Roger
1   2017    Rafa
2   2018    Roger
3   2019    Rafa
4   2019    Novak
5   2019    Dom

into this binary matrix:

>>> df_out

    Roger   Rafa    Novak   Dom
dates               
2017    1   1   0   0
2018    1   0   0   0
2019    0   1   1   1

with all the dates as index, all the names as columns, and the data being 1 if occurence of the name at the date, and np.NaN or 0 if not.

I can build the df_out dataframe with its index and columns, but how would you get the data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use get_dummies with max for 1 if exist values else 0:

df = pd.get_dummies(df_in.set_index('dates')['names']).groupby(level=0).max()
print (df)
       Dom  Novak  Rafa  Roger
dates                         
2017     0      0     1      1
2018     0      0     0      1
2019     1      1     1      0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...