Вы можете использовать defaultdict
для значений хранения - первый столбец zip с ci
, зациклить их с Counter
и добавить, если c1 == 0
добавить отрицательные значения.
Последний фильтр только положительный или 0
учитывается в словаре:
from collections import Counter, defaultdict
zipped = zip(df['text'], df['c1'])
d = defaultdict(int)
for a, b in zipped:
c = Counter(set(a.lower().split()))
for k, v in c.items():
if b == 0:
v = -v
d[k] += v
d = {k: v for k, v in d.items() if v > 0}
print (d)
{'are': 1, 'hello': 2, 'how': 1,'people': 1, 'world': 1, 'you': 1, 'i': 1, 'am': 1, 'fine': 1}
Аналогичное решение, если значение в c1
отсортировано - сначала все 1
, а затем все 0
:
from collections import Counter, defaultdict
df = df.sort_values('c1', ascending=False)
zipped = zip(df['text'], df['c1'])
d = defaultdict(int)
for a, b in zipped:
c = Counter(set(a.lower().split()))
for k, v in c.items():
if (b == 0) and (k in d):
d[k] -= v
elif (b == 1):
d[k] += v
print (d)
defaultdict(<class 'int'>, {'are': 1, 'hello': 2, 'how': 1, 'people': 1,
'world': 1, 'you': 1, 'i': 1, 'am': 1, 'fine': 1})
df = pd.DataFrame({'val': list(d.keys()),
'No': list(d.values())}).sort_values('No', ascending=False)
print (df)
val No
1 hello 2
0 are 1
2 how 1
3 people 1
4 world 1
5 you 1
6 i 1
7 am 1
8 fine 1
s = pd.Series(d).sort_values(ascending=False)
print (s)
hello 2
fine 1
am 1
i 1
you 1
world 1
people 1
how 1
are 1
dtype: int64