如何计算dataframe上列表中的特定字符串元素?

b4qexyjb  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(645)

我有以下清单:

  1. mylist = ['pages', 'disable', 'sensitive', 'application', 'screen', 'login', 'dynamic', 'frida', 'use', 'capture', 'stronger', 'flag_secure', 'strengthen', 'default', 'registration', 'obfuscate', 'anti', 'feature', 'protection', 'blurring', 'appsview', 'instrumentation', 'recent', 'paste', 'copy', 'exported', 'improve', 'mechanism', 'device', 'encryption', 'information', 'version', 'code', 'components', 'restrict', 'access', 'data', 'adding', 'debugger', 'otp', 'runtime', 'server', 'instrument', 'ensure', 'input', 'link', 'special', 'magisk', 'magic', 'obfuscation']

我有一个数据框,其中包含一组字符串:

  1. 0 Implement stronger root detection and adding debugger or dynamic instrument detection at runtime.
  2. 1 Strengthen root detection and implement Frida detection.
  3. 2 Implement code obfuscation to the application.
  4. 3 Disable screen capture by default and use FLAG_SECURE.
  5. 4 Implement screen blurring on the Recent Apps view.

如何计算数据框上mylist中每个元素的出现次数,并按其值计数对其进行排序?
这就是我希望得到的结果:

  1. Word Count
  2. pages 31
  3. disable 25
  4. sensitive 6

我怎样才能做到这一点?

qxgroojn

qxgroojn1#

您的预期输出与给定的示例数据不匹配。
首先可以在空间上拆分列,然后 strip 去掉任何剩余的空格或句号和逗号,然后分解它,然后调用 value_countsreindex 在列表中,最后删除 NaN 值,并按降序对值进行排序。
它假定 case-sensitive 计数。

  1. # df is the dataframe, and text is the column name
  2. >>> result=(df['text']
  3. .str
  4. .split()
  5. .apply(lambda x: [i.strip(' .,') for i in x])
  6. .explode()
  7. .value_counts()
  8. .reindex(mylist)
  9. .dropna()
  10. .sort_values(ascending=False))

输出:

  1. >>> result
  2. screen 2.0
  3. application 1.0
  4. dynamic 1.0
  5. use 1.0
  6. capture 1.0
  7. stronger 1.0
  8. default 1.0
  9. blurring 1.0
  10. code 1.0
  11. adding 1.0
  12. debugger 1.0
  13. runtime 1.0
  14. instrument 1.0
  15. obfuscation 1.0
  16. Name: text, dtype: float64
展开查看全部
gdrx4gfi

gdrx4gfi2#

我希望我已经很好地理解了你的问题。这个例子适用于所有的单词 mylist 并统计 Dataframe 中的出现次数 df ( df["col1"] 您的列是否包含字符串):

  1. df_out = pd.DataFrame({"Word": mylist})
  2. df_out["Count"] = df_out["Word"].apply(
  3. lambda x: df["col1"]
  4. .apply(lambda z: sum(x in w for w in z.lower().split()))
  5. .sum()
  6. )
  7. print(df_out[df_out.Count > 0].sort_values(by="Count", ascending=False))

印刷品:

  1. Word Count
  2. 4 screen 2
  3. 1 disable 1
  4. 13 default 1
  5. 42 instrument 1
  6. 40 runtime 1
  7. 38 debugger 1
  8. 37 adding 1
  9. 32 code 1
  10. 22 recent 1
  11. 19 blurring 1
  12. 12 strengthen 1
  13. 3 application 1
  14. 11 flag_secure 1
  15. 10 stronger 1
  16. 9 capture 1
  17. 8 use 1
  18. 7 frida 1
  19. 6 dynamic 1
  20. 49 obfuscation 1
展开查看全部

相关问题