python - 从python中数据框中的特定列创建列表
问题描述
我有以下数据集地址' https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/Visualization/Online_Retail/Online_Retail.csv '
我使用以下代码导入
online_rt = pd.read_csv('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Online_Retail/Online_Retail.csv', delimiter = ',')
online_rt.head()
这个代码过滤掉一些特定的数据点
Quantity_sum = online_rt.groupby(['Country'])[['Quantity']].sum().sort_values('Quantity', ascending=False)
Top_10 = Quantity_sum.iloc[1:11,:]
现在我想要的是将 Country 列转换为单独的列表,将 Quantity 列转换为单独的列表
我用了
Top_10['Country'].tolist()
一列
和
Top_10['Quantity'].tolist()
对于另一列
但它一直给我 KeyError :
第一个列表的“国家”和第二个列表的 KeyError:“数量”
如何为我的数据制作两个单独的列表?
解决方案
在groupby
生成的数据框Quantity_sum
只有一列之后:Quantity
,而该Country
列现在是索引。
In [66]: Quantity_sum.head()
Out[66]:
Quantity
Country
United Kingdom 4263829
Netherlands 200128
EIRE 142637
Germany 117448
France 110480
为了获取国家/地区列表,您必须通过数据框的index
属性访问它,如下所示:
In [67]: Top_10.index.tolist()
Out[67]:
['Netherlands',
'EIRE',
'Germany',
'France',
'Australia',
'Sweden',
'Switzerland',
'Spain',
'Japan',
'Belgium']
对于Quantity
您所做的似乎是正确的并且对我有用:
In [68]: Top_10['Quantity'].tolist()
Out[68]: [200128, 142637, 117448, 110480, 83653, 35637, 30325, 26824, 25218, 23152]
推荐阅读
- c# - 如何在 wix 中实现安装程序进度条的回滚?
- azure-devops-extensions - 如果任何 AzureDevops 构建代理不可用,如何获得警报?
- c# - 单击按钮时显示 2 个用户输入变量的结果
- python - 在linux中升级python
- c# - c# 获取公共频道 Telegram without Bot Api 和 Telegram Api 的特别帖子
- php - WooCommerce 自定义订单操作不适用于垃圾状态
- azure - 使用 AzureFileCopy 任务覆盖 Azure Blob 存储中的文件
- javascript - 用户事件后的 Wordpress Enqueue 脚本,例如点击
- python - 如何绘制整齐的 ImageGrid 图?
- reactjs - 在单个 Axios POST 请求中发送 FormData 对象和文件