#python #list #dataframe #group-by #count
Вопрос:
У меня есть этот список:
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']
И у меня есть этот фрейм данных, который содержал кучу строк:
0 Implement stronger root detection and adding debugger or dynamic instrument detection at runtime.
1 Strengthen root detection and implement Frida detection.
2 Implement code obfuscation to the application.
3 Disable screen capture by default and use FLAG_SECURE.
4 Implement screen blurring on the Recent Apps view.
Как я могу подсчитать вхождения каждого элемента в mylist во фрейме данных и отсортировать его по количеству значений?
Это то, что я хотел бы получить в результате:
Word Count
pages 31
disable 25
sensitive 6
Как я могу этого достичь?
Комментарии:
1. Почему там указан этот номер
0
mylist
? Следует ли игнорировать цифры?2. О, просто не обращай внимания на цифры..
3. Добро пожаловать в ИТАК, что вы пробовали до сих пор и где вы застряли?
Ответ №1:
Ваш ожидаемый результат не совпадает с данными данного образца.
Вы можете начать с разделения столбца на пробелы, затем strip
удалить все оставшиеся пробелы или пробелы и запятые, затем развернуть его, затем вызвать value_counts
и reindex
в списке, наконец, удалить NaN
значения и отсортировать значения в порядке убывания.
Это предполагает case-sensitive
подсчеты.
#df is the dataframe, and text is the column name
>>> result=(df['text']
.str
.split()
.apply(lambda x: [i.strip(' .,') for i in x])
.explode()
.value_counts()
.reindex(mylist)
.dropna()
.sort_values(ascending=False))
выход:
>>> result
screen 2.0
application 1.0
dynamic 1.0
use 1.0
capture 1.0
stronger 1.0
default 1.0
blurring 1.0
code 1.0
adding 1.0
debugger 1.0
runtime 1.0
instrument 1.0
obfuscation 1.0
Name: text, dtype: float64
Ответ №2:
Надеюсь, я хорошо понял ваш вопрос. Этот пример будет использоваться для каждого слова mylist
и подсчета вхождений в df
кадре данных ( ваши df["col1"]
столбцы со строками):
df_out = pd.DataFrame({"Word": mylist})
df_out["Count"] = df_out["Word"].apply(
lambda x: df["col1"]
.apply(lambda z: sum(x in w for w in z.lower().split()))
.sum()
)
print(df_out[df_out.Count > 0].sort_values(by="Count", ascending=False))
С принтами:
Word Count
4 screen 2
1 disable 1
13 default 1
42 instrument 1
40 runtime 1
38 debugger 1
37 adding 1
32 code 1
22 recent 1
19 blurring 1
12 strengthen 1
3 application 1
11 flag_secure 1
10 stronger 1
9 capture 1
8 use 1
7 frida 1
6 dynamic 1
49 obfuscation 1