无法计算Pandas中基于货币的列数据的总和

时间:2017-08-18 19:32:18

标签: python python-3.x pandas numpy data-science

我有以下CSV数据:

+----------+-------------+-------+---------+
| Category | Part Number | Units |  Cost   |
+----------+-------------+-------+---------+
| Axel     |          78 |   587 | $159.95 |
| Rim      |          48 |   234 | $38.75  |
| Nut      |          39 |  1234 | $0.15   |
| Axel     |          79 |    67 | $110.95 |
+----------+-------------+-------+---------+

以下代码:

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
df = pd.read_csv('stock.csv',engine="python")

#Sum of values by category
df.groupby('Category').sum()['Units']
df.groupby('Category').sum()['Cost']

当我运行倒数第二行时,我得到以下输出:

df.groupby('Category').sum()['Units']
Out[4]: 
Category
Axel     654
Nut     1234
Rim      234
Name: Units, dtype: int64

当我运行最后一行时,我收到以下错误:

KeyError: 'Cost'

我不确定是否有一种简单的方法来对数据求和,而不将数据类型转换为整数然后将其转换回来。

1 个答案:

答案 0 :(得分:2)

var app = angular.module('Blog', []); app.factory('blogpostservice', ['$http', function ($http) { this.getMoreData = function (pagecount) { return $http.get('/api/posts/' + pagecount); } }]); app.controller('MainController', ['$scope', 'blogpostservice', function ($scope, blogpostservice) { $scope.pagec = 1; $scope.posts = []; this.getMoreData = function (posts) { blogpostservice.getMoreData(pagec).success(function () { alert('got it successfully!!!'); }).error(function () { alert('something went wrong!!!'); }); } }]); 忽略所有非数字列。您必须先将成本转换为数字:

.sum()