我有一个名为pd的熊猫数据帧。我尝试使用嵌套for循环来迭代dataframe的每个元组,并在每次迭代时将元组与该帧中的所有其他元组进行比较。在比较步骤中,我使用Python的difflib.SequenceMatcher().ratio()和删除具有高度相似性的元组(ratio>;0.8)。你知道吗
问题: 不幸的是,在第一次外循环迭代之后,我得到了一个KeyError。你知道吗
我怀疑,通过删除元组,我使外循环的索引器无效。或者,我试图访问一个不存在(已删除)的元素,从而使内部循环的索引器无效。你知道吗
代码如下:
import json
import pandas as pd
import pyreadline
import pprint
from difflib import SequenceMatcher
# Note, this file, 'tweetsR.json', was originally csv, but has been translated to json.
with open("twitter data/tweetsR.json", "r") as read_file:
data = json.load(read_file) # Load the source data set, esport tweets.
df = pd.DataFrame(data) # Load data into a pandas(pd) data frame for pandas utilities.
df = df.drop_duplicates(['text'], keep='first') # Drop tweets with identical text content. Note,
these tweets are likely reposts/retweets, etc.
df = df.reset_index(drop=True) # Adjust the index to reflect dropping of duplicates.
def duplicates(df):
for ind in df.index:
a = df['text'][ind]
for indd in df.index:
if indd != 26747: # Trying to prevent an overstep keyError here
b = df['text'][indd+1]
if similar(a,b) >= 0.80:
df.drop((indd+1), inplace=True)
print(str(ind) + "Completed") # Debugging statement, tells us which iterations have completed
duplicates(df)
有人能帮我理解和/或修复它吗?你知道吗
@KazuyaHatta提到的一个解决方案是itertools.组合(). 虽然,我使用它的方式(可能还有另一种方式)是O(n^2)。因此,在本例中,有27000个元组,需要迭代的组合接近357714378个(太长)。你知道吗
代码如下:
我的下一步,正如@KazuyaHatta所描述的,是尝试通过蒙版的方法进行投放。你知道吗
注意:很遗憾,我无法发布数据集的样本。你知道吗
相关问题 更多 >
编程相关推荐