首页 > 解决方案 > 删除行 < x 以在 Pandas 中创建绘图

问题描述

我在 .csv 中有一个这样的数据框:

Consequence,N_samples
A,227
B,413
C,194
D,1
E,1610
F,10
G,7
H,1
I,1
J,5
K,1
L,5
M,5
N,30
O,7
P,3

我想从中制作一个情节饼,但将所有低于 150 的值归为“其他”类别。我试过运行这段代码,但它不起作用。

import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plotother = {'Consequence' : 'Other', 'N_samples':0}
df=pd.read_csv('df.csv', sep=',')
df = df.append(other,ignore_index=True)
for i in df:
  if (x in df['N_samples']) < 150:
       df['N_samples'].iloc[-1]=df['N_samples'].iloc[-1] + (x in df['N_samples'])
       df.drop([x])
df.plot.pie(label="", title="Consequence", startangle=90);
plot.savefig('Consequence.svg')

一旦我运行它,我会收到以下错误:

KeyError: "['Consequence'] not found in axis"

我真的很感激任何帮助。

标签: pythonpandasdataframe

解决方案


你让它变得比现在更困难。

首先获取样本大小低于 150 的所有行:

small_sizes = df[df['N_Samples']<150]

总结他们的价值观:

other_samples = small_sizes['N_Samples'].sum()

最后删除行并添加other行:

df = df[~df['N_Samples']<150]
df.loc['other','N_samples'] = other_samples

这应该够了吧。


推荐阅读