Удалить количество строк в кадре данных - PullRequest
0 голосов
/ 01 декабря 2018

У меня есть фрейм данных, содержащий 25000 строк с двумя столбцами (текст, класс), класс содержит число [A, B, C]

data = pd.read_csv('E:\mydata.txt', sep="*")
data.columns = ["text", "class"]

Мне нужно удалить, например, 10 строк класса A,15 рядов класса B

Ответы [ 2 ]

0 голосов
/ 02 декабря 2018

Вы можете создать одну логическую маску с помощью np.logical_and и groupby.cumcount.Затем примените его к вашему фрейму данных через iloc:

# example dataframe
df = pd.DataFrame({'group': np.random.randint(0, 3, 100),
                   'value': np.random.random(100)})

print(df.shape)  # (100, 2)

# criteria input
criteria = {1: 10, 2: 15}

# cumulative count by group
cum_count = df.groupby('group').cumcount()

# Boolean mask, negative via ~
conditions = [(df['group'].eq(k) & cum_count.lt(v)) for k, v in criteria.items()]
mask = ~np.logical_or.reduce(conditions)

# apply Boolean mask
res = df.iloc[mask]

print(res.shape)  # (75, 2)
0 голосов
/ 01 декабря 2018

Этого можно добиться с помощью условного среза и свойства индекса для фреймов данных

remove_n = 10
remove_class = 1
# Here you first find the indexes where class is equal to the class you want to drop.
#Then you slice only the first n indexes of this class
index_to_drop = data.index[data['class'] == remove_class][:remove_n]
#Finally drop those indexes
data = data.drop(index_to_drop)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...