Schematic illustration of the number of values in each column of the data frame using pandas

Asked 2 years ago, Updated 2 years ago, 44 views

For example

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

If you have this kind of data, you can use Panda's, Numpi, a b c def g for each attribute Is there a way to summarize the whole data in such a way that a has two 1s, b has two 2s, and 1s? And I want to know if there's a way to diagram the summarized data into a graph or something I'm asking you a question because I searched the Internet hard but it didn't come out well.

pandas python

2022-09-20 19:22

1 Answers

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()


2022-09-20 19:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.