作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个包含费用 list 的文件:
示例:
date item out in
12/01/2017 PAGO FIBERTEL 668.5 0.0
12/01/2017 PAGO GAS NATURAL 2.32 0.0
10/02/2017 EXTRACCION TARJETA 1200.0 0.0
10/02/2017 CPA. STARBUCKS R. PE9A 105.0 0.0
10/02/2017 CPA. STARBUCKS R. PE9A 125.0 0.0
11/03/2017 EXTRACCION TARJETA 1200.0 0.0
11/03/2017 SALES 0.0 10000.0
我想制作一个情节,在其中我可以看到一些项目在一年中每个月是如何演变的。例如,我将使用“startbucks”作为关键字过滤“item”列,我将计算每月汇总并显示如下信息:
Dec Jan Mar
Starbucks 0 0 230
我从 json 文件中获取了一个关键字列表,我将使用它来生成每一行。然而,我无法仅用一个来做到这一点。我已经尝试了几种形式的 groupby (带石斑鱼和不带石斑鱼),但我认为我不明白。这是我目前得到的代码:
import pandas as pd
import matplotlib.pyplot as plt
import sys
import json
class Banca():
def __init__(self, name, csv_path, json_path):
self.name= name
self.df = pd.read_csv(csv_path)
with open(json_path) as j:
self.json = json.load(j)
def prepare(self):
#Add header
headers = ['fecha','concepto','in','out',"x"]
self.df.columns = headers
#fix data
self.df.fecha = pd.to_datetime(self.df.fecha)
#Here i'm testing, this doesnt work
g1=self.df.groupby(pd.Grouper(key='fecha', freq='M')['in'].sum())
print(g1.describe().to_string())
print(g1.head())
#g1.plot(y='out', style='.-', figsize=(15,4))
#plt.show()
#filter data
# some filter
def grafica(self):
#plot data
self.df.plot(x='fecha', y='out',style='.-', figsize=(15,4))
plt.show()
def test_df(self):
print(self.df.describe(include='all'))
def test_json(self):
for x,y in self.json.items():
print(x,y)
icbc = Banca("ICBC", sys.argv[1], sys.argv[2])
icbc.test_df()
icbc.prepare()
#icbc.grafica()
#icbc.test_json()
我编写此代码是为了学习使用 pandas 进行数据操作的练习。我已经学习了很多文章,但我已经被困在这里有一段时间了。我在想也许我不应该使用 groupby 来实现这个目的,而是使用其他东西。不管怎样,我很感谢任何帮助。
最佳答案
用途:
#convert column to datetimes if necessary
df['fecha'] = pd.to_datetime(df['fecha'], format='%d/%m/%Y')
print(df)
fecha concepto in out
0 2017-01-12 PAGO FIBERTEL 668.50 0.0
1 2017-01-12 PAGO GAS NATURAL 2.32 0.0
2 2017-02-10 EXTRACCION TARJETA 1200.00 0.0
3 2017-02-10 CPA. STARBUCKS R. PE9A 105.00 0.0
4 2017-02-10 CPA. STARBUCKS R. PE9A 125.00 0.0
5 2017-03-11 EXTRACCION TARJETA 1200.00 0.0
6 2017-03-11 SALES 0.00 10000.0
import re
#create DatetimeIndex
df = df.set_index('fecha')
#list of values
L = ['starbuck','pago']
all_s = []
for x in L:
#filter by substrings, select column in
s = df.loc[df['concepto'].str.contains(x, flags=re.I), 'in']
#aggregate by months and sum
s = s.groupby(pd.Grouper(freq='M')).sum()
#change format of index by `MM-YYYY`
s.index = s.index.strftime('%b-%Y')
all_s.append(s.rename(x))
#join all Series together and transpose
df = pd.concat(all_s, axis=1).T
print (df)
Feb-2017 Jan-2017
starbuck 230.0 NaN
pago NaN 670.82
编辑:
对于绘图,应该更好地按关键字绘制 DatetimeIndex
和列,还按 MS
分组开始月份并添加 asfreq
如果要添加缺失的月份,则用 0
填充:
df['fecha'] = pd.to_datetime(df['fecha'], format='%d/%m/%Y')
print(df)
fecha concepto in out
0 2017-01-12 PAGO FIBERTEL 668.50 0.0
1 2017-01-12 PAGO GAS NATURAL 2.32 0.0
2 2017-02-10 EXTRACCION TARJETA 1200.00 0.0
3 2017-02-10 CPA. STARBUCKS R. PE9A 105.00 0.0
4 2017-02-10 CPA. STARBUCKS R. PE9A 125.00 0.0
5 2017-03-11 EXTRACCION TARJETA 1200.00 0.0
6 2017-05-11 SALES 20.00 10000.0 <-changed last month
<小时/>
import re
df = df.set_index('fecha')
L = ['starbuck','pago', 'sales']
all_s = []
for x in L:
s = df.loc[df['concepto'].str.contains(x, flags=re.I), 'in']
s = s.groupby(pd.Grouper(freq='MS')).sum()
all_s.append(s.rename(x))
df = pd.concat(all_s, axis=1).fillna(0).asfreq('MS', fill_value=0)
print (df)
starbuck pago sales
fecha
2017-01-01 0.0 670.82 0.0
2017-02-01 230.0 0.00 0.0
2017-03-01 0.0 0.00 0.0
2017-04-01 0.0 0.00 0.0
2017-05-01 0.0 0.00 20.0
df.plot(style='.-', figsize=(15,4))
关于python - 用 pandas 计算每月的支出总额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51914445/
我有一张像这张照片的 table : enter image description here 我想添加一个期末余额列,它将是 =sum(income)-sum(expenses) 按日期计算 (例如
我是一名优秀的程序员,十分优秀!