【发布时间】:2021-11-25 05:02:17
【问题描述】:
我想在 Counter 对象上做一个双循环,这是两个不同的计数器相减的结果。 我的计数器是这样的:
{'sun': 5,
'abstract': 0.0,
'action': 10,
'ad': 0.0,
....}
我有一个像这样的数据框:
0 1
0 sun sunlight
2 river water
3 stair staircase
4 morning sunrise
n ......
我的目的是在数据框中只保留几个单词,该行的第一个单词的频率为 0,第二个单词的频率大于 0(或者相反,第一个单词大于 0,第二个单词大于 0,所以不包括耦合两个 0 频率或两个大于零频率)。
我试过这样做,但是太慢了(需要5个多小时才能完成):
for i,j in counter_diff.items(): #extract i word and j counter number of a item
for t,k in counter_diff.items(): #extract t word and k counter number of a item
for s in range(len(df)):
if ((df[0][s] == i and j==0) and (df[1][s] == t and k==0)):
df = df.drop([s])
elif ((df[0][s] == i and j>0) and (df[1][s] == t and k>0)):
df = df.drop([s])
df = df.reset_index(drop=True)
您有什么更好的方法建议吗? 感谢您的宝贵时间!
【问题讨论】:
-
你为什么一开始就在柜台上进行迭代?
-
检查计数器中与数据框中的单词匹配的单词。计数器是在不同的单词列表上创建的。
-
Counter对象如何获取计数为零的元素? -
@Radix 完全否定了这一点。计数器是
dict。您只需直接访问字典中的键。不要遍历字典。 -
在数据框中创建两个额外的列来映射字典中的值。然后使用向量化操作根据这些列过滤行
标签: python dataframe for-loop counter