【发布时间】:2019-12-09 00:41:33
【问题描述】:
考虑到 3 列,我想删除那些特定值在一列中只出现一次的行。也就是说,对于功能:
- 文本:如果 value_counts() == 1,则消除这些行,或者仅在 value_counts() > 1 时保留
- next_word:如果 value_counts() == 1,则消除这些行,或者仅在 value_counts() > 1 时保留。在这种情况下,只需使用已处理的行(仅保留“文本”列包含的行值出现多次)
- previous_word:如果 value_counts() == 1,则消除这些行,或者仅在 value_counts() > 1 时保留。在这种情况下,使用已处理的案例(只保留列“文本”和'next_word' 包含多次出现的值)
我已经尝试过获取一个数据框,该数据框保留包含特定列中这些值的行:
#text
text_counts = df_processed['text'].value_counts()
text_list = text_counts[text_counts > 1].index.tolist()
zip_data_text_removed = df_processed[df_processed['text'].isin(text_list)]
如果我显示此特定列“文本”的 value_counts:zip_data_text_removed.text.value_counts()
我可以检查我得到的数据框是否包含多次出现的值,即 50539 个初始唯一值中的 25470 个唯一值(这是正确的)。但是,当我显示有关数据框的信息时:
类'pandas.core.frame.DataFrame' Int64Index:291442 个条目,0 到 316510
显然不匹配。
我还想对其余列应用相同的方法(现在,使用之前的过滤数据框):
#Next
next_word_counts = df_processed['next_word'].value_counts()
next_word_list = next_word_counts[next_word_counts > 1].index.tolist()
zip_data_next_text_removed = zip_data_text_removed[zip_data_text_removed['next_word'].isin(next_word_list)]
#Previous
previous_word_counts = df_processed['previous_word'].value_counts()
previous_word_list = previous_word_counts[previous_word_counts > 1].index.tolist()
zip_data_prev_text_removed = zip_data_next_text_removed[zip_data_next_text_removed['previous_word'].isin(previous_word_list)]
但是,当我显示“文本”的 value_counts 时,即使用的第一个功能:
zip_data_prev_text_removed.text.value_counts()
它还显示仅出现一次的值.. 这很奇怪。数据框的信息也比较混乱:
类'pandas.core.frame.DataFrame' Int64Index:247621 个条目,0 到 316509
不应该是从 0 到 247621 个条目吗?
***编辑
现在,我按照@janPansky 的建议添加了 reset_index(drop=True):
#text
text_counts = df_processed['text'].value_counts()
text_list = text_counts[text_counts > 1].index.tolist()
zip_data_text_removed = df_processed[df_processed['text'].isin(text_list)]
zip_data_text_removed = zip_data_text_removed.reset_index(drop=True)
#Next
next_word_counts = zip_data_text_removed['next_word'].value_counts()
next_word_list = next_word_counts[next_word_counts > 1].index.tolist()
zip_data_next_text_removed = zip_data_text_removed[zip_data_text_removed['next_word'].isin(next_word_list)]
zip_data_next_text_removed = zip_data_next_text_removed.reset_index(drop=True)
print(zip_data_next_text_removed.text.value_counts() )
但是,仍然继续打印 value_count == 1 的值
【问题讨论】:
-
在不重置索引的情况下删除行之前是否进行了一些操作?
-
@Mayeulsgc 是的,只是将某些列的值转换为小写: df_processed['text'] = df_processed['text'].apply(lambda x: x.lower())
-
你能澄清你在第一句话中的意思吗?您是否要删除所有具有仅在三列中的任何一列中出现一次的值的行?或者您是否尝试删除具有在所有列中出现一次的值的行?
-
@maltodextrin 在第一个原始帖子中查看上面的编辑