簡體   English   中英

如何為每一列值,按另一列值分組,返回百分比?

[英]How to for each column value, grouped by another column values, return percentage ratio?

這是一個復雜的問題,我不知道如何制定問題,只需復制粘貼下面的代碼即可查看采樣數據幀(原始有>百萬行):

df = pd.DataFrame({'App ID': {0: 'com.hindise.hindisahitya',
  1: 'com.hindise.hindisahitya',
  2: 'com.hindise.hindisahitya',
  3: 'com.hindise.hindisahitya',
  4: 'com.finwizard.fisdom',
  5: 'com.finwizard.fisdom',
  6: 'com.finwizard.fisdom',
  7: 'com.finwizard.fisdom',
  8: 'com.finwizard.fisdom',
  9: 'com.finwizard.fisdom',
  10: 'com.finwizard.fisdom',
  11: 'com.finwizard.fisdom',
  12: 'com.hindise.hindisahitya',
  13: 'com.hindise.hindisahitya',
  14: 'com.hindise.hindisahitya',
  15: 'com.hindise.hindisahitya',
  16: 'org.altruist.BajajExperia',
  17: 'org.altruist.BajajExperia',
  18: 'org.altruist.BajajExperia',
  19: 'org.altruist.BajajExperia'},
 'Star': {0: 3,
  1: 5,
  2: 5,
  3: 4,
  4: 5,
  5: 1,
  6: 1,
  7: 1,
  8: 5,
  9: 1,
  10: 1,
  11: 1,
  12: 3,
  13: 5,
  14: 5,
  15: 4,
  16: 5,
  17: 1,
  18: 1,
  19: 1},
 'Text': {0: 'No thats okay ...I Found some network issue in my phone that is by your app is not working properly ...but now its working thanks for your Quick reaction !',
  1: 'its a great app evr for preparation for govt exams or very useful for the great knowledge! about our religious books and thoughts',
  2: "I just loved it ..I don't know if it helps in clarifying net exam or not but surely it is increasing my knowledge and because of this app I made myself somewhat busy 😊",
  3: 'Its aap very useful for us. This aap give us smart idea prepration for exam.',
  4: "Have been using Fisdok for 2 + years now for MF and other investments. Pros 1. The interface is clean and easy to surf 2. The customer service is very good with short response time 3. Over the last two years, the number of funds on the platform have increased, giving more and better choices to the users Cons 1. You can't search the MF of your choice. You will have to 'discover' them.",
  5: "Bad application. Showing fake data. Already one year I invested. I am in loss. Don't download or invest. Showing fake data to attract customers. 80%,90% but actually it's minus 20% result. Waste of time and money.",
  6: 'Lags Too Much , App Freeze on Option Data Screen , when i open F&O Section . whenever i try to open Nifty50 Option Chain ,app starts Lagging & app forced close , Too Much App Freeze Problem, Buggy app , Lags too much , my device :- Oneplus 7 Pro 256 GB / 8 GB Ram',
  7: 'In other categories section, it shows nothing! Just goes blank!! Tried almost 20 times from last 2 days!! After a year problem is the same!!',
  8: "Have been using Fisdok for 2 + years now for MF and other investments. Pros 1. The interface is clean and easy to surf 2. The customer service is very good with short response time 3. Over the last two years, the number of funds on the platform have increased, giving more and better choices to the users Cons 1. You can't search the MF of your choice. You will have to 'discover' them.",
  9: "Bad application. Showing fake data. Already one year I invested. I am in loss. Don't download or invest. Showing fake data to attract customers. 80%,90% but actually it's minus 20% result. Waste of time and money.",
  10: 'Lags Too Much , App Freeze on Option Data Screen , when i open F&O Section . whenever i try to open Nifty50 Option Chain ,app starts Lagging & app forced close , Too Much App Freeze Problem, Buggy app , Lags too much , my device :- Oneplus 7 Pro 256 GB / 8 GB Ram',
  11: 'In other categories section, it shows nothing! Just goes blank!! Tried almost 20 times from last 2 days!! After a year problem is the same!!',
  12: 'No thats okay ...I Found some network issue in my phone that is by your app is not working properly ...but now its working thanks for your Quick reaction !',
  13: 'its a great app evr for preparation for govt exams or very useful for the great knowledge! about our religious books and thoughts',
  14: "I just loved it ..I don't know if it helps in clarifying net exam or not but surely it is increasing my knowledge and because of this app I made myself somewhat busy 😊",
  15: 'Its aap very useful for us. This aap give us smart idea prepration for exam.',
  16: 'Amazing app. I have never faced any kind of issue while doing every transactions. It is hassle-free and smooth to use. Very nice ui design as well. No issue while navigating between multiple services. Truly amazing app and the online services offered are very useful and easy navigation between each operation. Totally hassle-free.You added some new features in every updates.',
  17: "My words may sound harsh, but yes this might be the worst responding app I have ever used. It takes way too long to load. After clicking on some options, it just keeps on loading and shows nothing. I never understood why is this happening?! Not only in my phone, I've checked in some other phones also. No difference! There are several other bugs. Development team have a LOT of works to do.",
  18: "Lost all my money paying bills here. They provided big offers, but don't fall for it. It's a scam! Paid electricity bill 3 days back, deducted the amount from bank. But it's still showing pending. There is no way we can talk to a customer service for payment purpose. There is no option to select the pending transaction when raising a dispute for payments. So I'm totally stuck and messed up. Lost almost 20% of my monthly income there. Can't sleep at night. I'm unable to contact anyone. Worst app",
  19: 'After entering OTP, the app now says "Multiple IDs found" and does not allow me to move further. In previous versions it used to show two accounts and I could choose from the list. Now I am unable to use this app at all because of this issue. It is not my fault that I have two IDs. I did not create these! Please provide the option to choose an Account ID after entering otp, just like I could earlier. Alternatively, if both the IDs can be merged, then help me with that atleast.'},
 'DeveloperReply': {0: 'Plz send issue email me we solve this problem',
  1: 'धन्यवाद',
  2: 'Dear User, thank you very much for sharing your valuable & useful feedback. If you have other feedback or suggestions, please write to us at hindise.net@gmail.com. We would love to hear from you!',
  3: '',
  4: '\nDear Nikita! Thank you for the positive rating. We’re really stoked about this. Thank you for investing with us.\n\n\n\n\n\n',
  5: '\nHey! Sorry to hear your experience was less than 5-stars. If you’re open to discussing your experience further, please write to us at sm@fisdom.com.\n\n\n\n\n\n\n',
  6: '\nHey! Sorry to hear your experience was less than 5-stars. If you’re open to discussing your experience further, please share the screen recording of the issue at sm@fisdom.com.',
  7: '\nDear Intzar Hussain Sihol! This is certainly not the experience we’d want any of our customers to have. Please fill this form and we will get in touch: htbit.ly/3ixhv9e\n\n\n\n\n\n\n\n\n',
  8: '\nDear Nikita! Thank you for the positive rating. We’re really stoked about this. Thank you for investing with us.\n\n\n\n\n\n',
  9: '\nHey! Sorry to hear your experience was less than 5-stars. If you’re open to discussing your experience further, please write to us at sm@fisdom.com.\n\n\n\n\n\n\n',
  10: '\nHey! Sorry to hear your experience was less than 5-stars. If you’re open to discussing your experience further, please share the screen recording of the issue at sm@fisdom.com.',
  11: '\nDear Intzar Hussain Sihol! This is certainly not the experience we’d want any of our customers to have. Please fill this form and we will get in touch: htpsbit.ly/3ixhv9e\n\n\n\n\n\n\n\n\n',
  12: 'Plz send issue email me we solve this problem',
  13: 'धन्यवाद',
  14: 'Dear User, thank you very much for sharing your valuable & useful feedback. If you have other feedback or suggestions, please write to us at hindise.net@gmail.com. We would love to hear from you!',
  15: '',
  16: 'Thank you so much for this 5-star review. We appreciate you being a customer and helping to share the word about us. We’re here for you anytime - Rashmi',
  17: 'Hi Anmol, we apologize for the inconvenience caused. We\'ve made a note of your feedback and fixed the same in our latest app version "7.1.1”. Please update your app & do revise your rating in case your issue is addressed. Thank you - Sagar',
  18: 'Hi Dilshad, Sorry for the inconvenience caused. However, we need more details to address your concern we suggest to visit our website www.bajajfinserv.in -> Click on "Contact us" -> Click on "Support" -> Click on "Email us" and share the required details for a quick resolution. Mention the ref ID EX092221-07 for us to track it. Thank you - Akshay',
  19: 'Hi Jyothi, Sorry for the inconvenience caused. However, we need more details to address your concern we suggest to visit our website www.bajajfinserv.in -> Click on "Contact us" -> Click on "Support" -> Click on "Email us" and share the required details for a quick resolution. Mention the ref ID EX102921-40 for us to track it. Thank you - Gurpreet'}})
df

對於按 Star(評級:0-1)分組的每個 App ID,我需要開發人員已回復的評論百分比。

Output:(如下所示)

Star       Percentage
0          10%
1          40%
2          30%
3          63.66%
4          23.1%
5          87.7%

您可以使用 pandas 的 groupby 和聚合 function :

df = df.groupby("Star").agg({"Text":"count", "DeveloperReply":lambda x: x.ne('').sum()})
df["Percentage"] = df["DeveloperReply"]/df["Text"] * 100 

使用 groupby: 參考

df_new=((df.groupby('Star').size()/df['Star'].count())*100).reset_index()
df_new.columns =['Star', 'per']

output

    Star per
0   1   45.0
1   3   10.0
2   4   10.0
3   5   35.0

您可以嘗試如下。

  • 首先,使用df.replace將“DeveloperReply”列中的所有空字符串替換為NaN值。
  • 在 ['App ID','Star']、select 列 'Text' 和 'DeveloperReply' 上使用df.groupby並獲取兩者的count
  • 將計算的百分比添加為新列,並重置索引。
import pandas as pd
import numpy as np

out = df.replace({'DeveloperReply':''},np.nan)\
    .groupby(['App ID','Star'])[['Text','DeveloperReply']].count()

out['Perc'] = out['DeveloperReply']/out['Text']*100
out.reset_index(drop=False, inplace=True)

print(out)

                      App ID  Star  Text  DeveloperReply   Perc
0       com.finwizard.fisdom     1     6               6  100.0
1       com.finwizard.fisdom     5     2               2  100.0
2   com.hindise.hindisahitya     3     2               2  100.0
3   com.hindise.hindisahitya     4     2               0    0.0
4   com.hindise.hindisahitya     5     4               4  100.0
5  org.altruist.BajajExperia     1     3               3  100.0
6  org.altruist.BajajExperia     5     1               1  100.0

如果您還想查看所有不在數據中的“App ID/Star”組合,您還可以將df.reindexitertools.product結合使用:

from itertools import product

out = df.replace({'DeveloperReply':''},np.nan)\
    .groupby(['App ID','Star'])[['Text','DeveloperReply']].count()

out['Perc'] = out['DeveloperReply']/out['Text']*100
# out.reset_index(drop=False, inplace=True)

out = out.reindex(list(product(df['App ID'].unique(),range(1,6))))
out.reset_index(drop=False, inplace=True)

print(out)

                       App ID  Star  Text  DeveloperReply   Perc
0    com.hindise.hindisahitya     1   NaN             NaN    NaN
1    com.hindise.hindisahitya     2   NaN             NaN    NaN
2    com.hindise.hindisahitya     3   2.0             2.0  100.0
3    com.hindise.hindisahitya     4   2.0             0.0    0.0
4    com.hindise.hindisahitya     5   4.0             4.0  100.0
5        com.finwizard.fisdom     1   6.0             6.0  100.0
6        com.finwizard.fisdom     2   NaN             NaN    NaN
7        com.finwizard.fisdom     3   NaN             NaN    NaN
8        com.finwizard.fisdom     4   NaN             NaN    NaN
9        com.finwizard.fisdom     5   2.0             2.0  100.0
10  org.altruist.BajajExperia     1   3.0             3.0  100.0
11  org.altruist.BajajExperia     2   NaN             NaN    NaN
12  org.altruist.BajajExperia     3   NaN             NaN    NaN
13  org.altruist.BajajExperia     4   NaN             NaN    NaN
14  org.altruist.BajajExperia     5   1.0             1.0  100.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM