python - 如何摆脱最后一列中的零
问题描述
我正在从事应用数据科学的任务。
问题: 将 % Renewable 分成 5 个垃圾箱。按大陆分组 Top15,以及这些新的 % Renewable 垃圾箱。每个组中有多少个国家?此函数应返回具有 MultiIndex 大陆的系列,然后是 % Renewable 的箱。不要包括没有国家的组。
这是我的代码:
def answer_twelve():
Top15 = answer_one()
ContinentDict = {'China':'Asia',
'United States':'North America',
'Japan':'Asia',
'United Kingdom':'Europe',
'Russian Federation':'Europe',
'Canada':'North America',
'Germany':'Europe',
'India':'Asia',
'France':'Europe',
'South Korea':'Asia',
'Italy':'Europe',
'Spain':'Europe',
'Iran':'Asia',
'Australia':'Australia',
'Brazil':'South America'}
Top15['Continent'] = Top15.index.to_series().map(ContinentDict)
Top15['bins'] = pd.cut(Top15['% Renewable'],5)
return pd.Series(Top15.groupby(by = ['Continent', 'bins']).size())#,apply(lambda x:s if x['Rank']==0 continue))
answer_twelve()
这是我上面代码的输出
Continent bins
Asia (2.212, 15.753] 4
(15.753, 29.227] 1
(29.227, 42.701] 0
(42.701, 56.174] 0
(56.174, 69.648] 0
Australia (2.212, 15.753] 1
(15.753, 29.227] 0
(29.227, 42.701] 0
(42.701, 56.174] 0
(56.174, 69.648] 0
Europe (2.212, 15.753] 1
(15.753, 29.227] 3
(29.227, 42.701] 2
(42.701, 56.174] 0
(56.174, 69.648] 0
North America (2.212, 15.753] 1
(15.753, 29.227] 0
(29.227, 42.701] 0
(42.701, 56.174] 0
(56.174, 69.648] 1
South America (2.212, 15.753] 0
(15.753, 29.227] 0
(29.227, 42.701] 0
(42.701, 56.174] 0
(56.174, 69.648] 1
dtype: int64
所需的输出是
Continent bins
Asia (2.212, 15.753] 4
(15.753, 29.227] 1
Australia (2.212, 15.753] 1
Europe (2.212, 15.753] 1
(15.753, 29.227] 3
(29.227, 42.701] 2
North America (2.212, 15.753] 1
(56.174, 69.648] 1
South America (56.174, 69.648] 1
Name: Countries, dtype: int64
我想摆脱零,我尝试使用
pd.Series(Top15.groupby(by = ['Continent', 'bins']).size().apply(lambda x:s if x['Rank']==0 continue))
但我不断收到以下错误
File "<ipython-input-317-14bc05bb2137>", line 20
return pd.Series(Top15.groupby(by = ['Continent', 'bins']).size().apply(lambda x:s if x['Rank']==0 continue))
^
SyntaxError: invalid syntax
我无法弄清楚我的错误。请帮我!
解决方案
使用 pandas 并在列为零时删除行
如果 column_name 是您的列:
df = df[df.column_name != 0]
推荐阅读
- reactjs - 如何在打字稿中调用 useHistory 函数
- c++ - Cmake qt项目链接错误(未定义符号:__declspec(dllimport))
- android - 将 TableLayout 转换为 RecyclerView
- google-cloud-platform - 如何配置 OBD2 跟踪器以发送和存储消息,例如 Google/Azure/WAS IoT
- metaprogramming - MT5/MQL5 如何用不同的货币进行 6 次交易
- replace - 在单个 Power BI Step/M 语句中更改字段类型和多个精确值替换
- python - 使用 Python 来“参与”Windows 的音频通道,类似于游戏或 youtube 视频,以避免在 7.1、5.1 等之间的不稳定切换
- c++ - 为什么我不应该将接口和实现放在一个文件中?
- django - 根据过滤的查询集有条件地在 Django admin 中显示列
- angular - 如何修复显示内存不足异常的 Ionic cordova 文档扫描仪