【问题标题】:Ignoring a set of categories忽略一组类别
【发布时间】:2018-07-21 22:21:24
【问题描述】:

我想从我的数据集的一个 excel 列(类别)中忽略几个类别。 我不得不删除“apple”(数据集中的一个类别),并且已经在代码中完成了。但是如何删除一组类别?我尝试使用列表和集合,但都不起作用。

例如,我想删除这些类别: ["Mango", "orange", ...]。 我怎样才能有效地做到这一点? 提前致谢。

数据集示例:

+----------------------+------------+
| Details              | Category   |
+----------------------+------------+
| Any raw text1        | Mango      |
+----------------------+------------+
| any raw text2        | Apple      |
+----------------------+------------+
| any raw text5        | Apple      |
+----------------------+------------+
| any raw text7        | Apple      |
+----------------------+------------+
| any raw text8        | Mango      |
+----------------------+------------+
| Any raw text4        | Berry      |
+----------------------+------------+
| any raw text5        | Orange     |
+----------------------+------------+
| any raw text6        | Apple      |
+----------------------+------------+

我的代码示例:

import pandas as pd
import numpy as np
import scipy as sp
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt  

data= pd.read_csv('Mydataset.xls', delimiter='\t',usecols=
['Details','Category'],encoding='utf-8')

target_one=data['Category']
target_list=data['Category'].unique()    

data=data[data.Category !="Apple"]
data=data[data.Category !="Mango"]
-----------------------------------

【问题讨论】:

  • 你能举一个初始excel文件的例子,你想忽略什么。也许您可以提及列名和一些示例数据
  • 如果您想忽略列中的几个值,您可以使用python函数自己读取csv文件并自己制作数据。 docs.python.org/3.1/library/csv.html
  • 谢谢@Teja,我已经添加了我的数据集,我想删除 apple,Mango,Orange Category 。我可以这样做: data=data[data.Category !="Apple"] data=data[data.Category !="Mango"] 但想减少行数。可能我可以使用列表来删除一组类别,但它不起作用。

标签: python-3.x pandas scikit-learn


【解决方案1】:

你需要这样的东西

# list of categories to be removed
category_toremove = ['Apple','Mango','Orange']

# use not operator with isin()
df = df[~df['Category'].isin(category_toremove)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2022-11-11
    • 2017-11-19
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多