pandas를 이용하여 데이터프레임의 각컬럼의 값의 갯수를 도식화하기

조회수 851회

예로들어

a  b  c  d  e  f  g
1  2  1  2  1  2  1
2  1  2  1  1  1  1
1  2  2  2  2  1  2

이런 데이터가 있다면 판다스,넘파이 등을 이용해서 a b c d e f g 각 속성에 대해서 a는 1이 2개, 2가 1개 b는 2가 2개 1이 1개 이런식으로 전체 데이터에 대해서 요약할 수 있는 방법이 있을까요? 그리고 요약된 데이터를 그래프 같은 걸로 도식화 하는 방법이 있는지 궁금합니다 인터넷 열심히 찾아봤는데 잘 안나와서 질문드립니다.

  • pandas 를 사용해서 작업하시고 도식화는 matplotlib 이나 seaborn 을 활용하면 됩니다. 정영훈 2020.12.4 16:36
  • value_counts nowp 2020.12.5 09:15

1 답변

  • Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license()" for more information.
    >>> txt = """a  b  c  d  e  f  g
    1  2  1  2  1  2  1
    2  1  2  1  1  1  1
    1  2  2  2  2  1  2"""
    >>> txt = txt.replace("  ", ",")
    >>> import pandas as pd
    >>> from io import StringIO
    >>> df = pd.read_csv(StringIO(txt))
    >>> df
       a  b  c  d  e  f  g
    0  1  2  1  2  1  2  1
    1  2  1  2  1  1  1  1
    2  1  2  2  2  2  1  2
    >>> df.a.value_counts()
    1    2
    2    1
    Name: a, dtype: int64
    >>> for col in df.columns:
        print("-----")
        print(col)
        print(df[col].value_counts())
    
    
    -----
    a
    1    2
    2    1
    Name: a, dtype: int64
    -----
    b
    2    2
    1    1
    Name: b, dtype: int64
    -----
    c
    2    2
    1    1
    Name: c, dtype: int64
    -----
    d
    2    2
    1    1
    Name: d, dtype: int64
    -----
    e
    1    2
    2    1
    Name: e, dtype: int64
    -----
    f
    1    2
    2    1
    Name: f, dtype: int64
    -----
    g
    1    2
    2    1
    Name: g, dtype: int64
    
    >>> df_vc = pd.DataFrame({ col:df[col].value_counts() for col in df.columns })
    >>> df_vc
       a  b  c  d  e  f  g
    1  2  1  1  1  2  2  2
    2  1  2  2  2  1  1  1
    
    >>> import matplotlib.pyplot as plt
    >>> df_vc.T.plot.bar(stacked=True)
    <AxesSubplot:>
    >>> plt.show()
    

    이미지

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)