Turn Pandas DataFrame of strings into histogram

后端 未结 3 1556
误落风尘
误落风尘 2020-12-31 03:40

Suppose I have a DataFrame of created like this:

import pandas as pd
s1 = pd.Series([\'a\', \'b\', \'a\', \'c\', \'a\', \'b\'])
s2 = pd.Series([\'a\', \'f\',         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 03:47

    Recreating the dataframe:

    import pandas as pd
    s1 = pd.Series(['a', 'b', 'a', 'c', 'a', 'b'])
    s2 = pd.Series(['a', 'f', 'a', 'd', 'a', 'f', 'f'])
    d = pd.DataFrame({'s1': s1, 's2': s2})
    

    To get the histogram with subplots as desired:

    d.apply(pd.value_counts).plot(kind='bar', subplots=True)
    

    enter image description here

    The OP mentioned pd.value_counts in the question. I think the missing piece is just that there is no reason to "manually" create the desired bar plot.

    The output from d.apply(pd.value_counts) is a pandas dataframe. We can plot the values like any other dataframe, and selecting the option subplots=True gives us what we want.

提交回复
热议问题