python - 删除行 < 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"
我真的很感激任何帮助。
解决方案
你让它变得比现在更困难。
首先获取样本大小低于 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
这应该够了吧。
推荐阅读
- pytest - Proboscis 可以与 Pytest 一起使用吗?
- c# - 验证 2 个组件具有相同的值
- reactjs - 如果找不到模块,如何捕获错误?
- c++ - 使用 reinterpret_cast c++ 后的意外行为
- webpack - 使用 SSR 与 IE11 反应 Redux - 客户端应用程序无法启动
- python - 如何向 music21 提交自定义特征提取方法?
- django - Django Rest Framework Post 嵌套模型
- cocoa - Why are my new subviews superposing in my splitview?
- java - 如何修复:嵌入式 H2 数据库“NonTransientError:无法读取该位置的页面”错误?
- python - 在一行中将元素追加并插入到列表中?