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개 이런식으로 전체 데이터에 대해서 요약할 수 있는 방법이 있을까요? 그리고 요약된 데이터를 그래프 같은 걸로 도식화 하는 방법이 있는지 궁금합니다 인터넷 열심히 찾아봤는데 잘 안나와서 질문드립니다.
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
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()
댓글 입력