Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hellow I have DataFrame like below:

df= pd.DataFrame({"target1" : [10, 0, 15, 10], "target2" : [50, 0, 20, 0], "ID" : ["1", "2", "3", "4"]})

And I need to create plot (bar or pie) which will show how % of ID have target1, how many target2, how many other (neither target1 nor target2).

I need results something like below:
T1 75% because 3 from 4 IDs have target1
T2 50% because 2 from 4 IDs have target2
other 25% because 1 from 4 do not have neither target1 nor target2

And I need have percentage description of columns and legend some if possible

enter image description here


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

1 Answer

My solution

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"target1": [10, 0, 15, 10], "target2": [50, 0, 20, 0], "ID": ["1", "2", "3", "4"]})
all = len(df["ID"])
value = [0, 0, 0]
for i in range(0, all):
    b = False
    if df["target1"][i] != 0:
        value[0] += 1
        b = True
    if df["target2"][i] != 0:
        value[1] += 1
        b = True
    if not b:
        value[2] += 1

# or you can use this
# value = [float(len([col for col in df["target1"] if col > 0])) / all * 100,
#            float(len([col for col in df["target2"] if col > 0])) / all * 100]
value = [(float(col) / all * 100) for col in value]
num_list = value
plt.bar(range(len(num_list)), num_list,
        tick_label=["target1 " + str(value[0]) + "%",
                    "target2 " + str(value[1]) + "%",
                    "default " + str(value[2]) + "%"])
plt.show()

effect


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...