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
1.5k views
in Technique[技术] by (71.8m points)

pandas - How to plot the frequency of the single elements of my column?

I have a little problem with my program.

I have a dataframe that looks like this:


Person     FavMovie
1          Ma Se Fr
2          Ma
3          Se Ma
4          Fr Ma
5          Se

I want to calculate the total frequency for Ma, Se and Fr and graph a barplot. However, I'm not sure about how to do that. I thought about creating a list,and then count in a loop the number of times I find a specific movie; I started writing the code this way:

favmovies_list = dataset['FavMovies'].tolist()
for element in favmovies_list:
        singlemovie = element.strip()
        print(singlemovie)

But it's clearly not working since I'm only separating the rows and not the single movies. Maybe there is another, more straightforward way, but I am a real beginner and I am not sure. Thank you very much in advance.

question from:https://stackoverflow.com/questions/65836797/how-to-plot-the-frequency-of-the-single-elements-of-my-column

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

1 Reply

0 votes
by (71.8m points)
d = pd.DataFrame({'Person':[1,2,3,4,5], 'FavMovie': ['Ma Se Fr', 'Ma', 'Se Ma', 'Fr Ma', 'Se']})

lst = d.FavMovie.tolist()

lst = [elem.strip().split() for elem in lst]
lst = [elem for sub_lst in lst for elem in sub_lst]

fig, ax = plt.subplots(1,1)
pd.DataFrame({'freq' : lst}).groupby('freq', as_index=True).size().plot(kind = 'bar', ax=ax)

fig # plot saved in fig

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

...