我使用Python Pandas并从Postgres加载这样一个表:
date v00 v01 v02 v03
2001-01-01 00:00:00 30 40 50 100
2001-01-01 00:00:00 80 120 20 60
2001-02-01 00:00:00 20 70 50 20
我想使用Pandas对日期行进行分组,并总结值。结果应该是这样的
2001-01-01 00:00:00 500
2001-02-01 00:00:00 160
我可以对日期进行分组并分别汇总值,但不能在一个视图中。你知道吗
我的结果是
1 220
2 280
3 160
以及
date v00 v01 v02 v03
2001-01-01 00:00:00 110 160 70 160
2001-02-01 00:00:00 20 70 50 20
这就是代码:
import psycopg2 as ps
import pandas as pd
import openpyxl
conn = ps.connect(host="host", user="user", password="password", dbname="Python_ueben")
cur = conn.cursor()
print('connect')
""" schema = input("Geben Sie das Schema ein")
table = input(" Geben Sie die Tabele ein") """
def load_data(schema, table):
sql_command = "SELECT * FROM {}.{};".format(str(schema), str(table))
print (sql_command)
# Load the data
data = pd.read_sql(sql_command, conn)
groub = data.groupby(['date']) # group Date and save in variable
print(data.sum(axis=1, skipna=True)) #sum values v00 - v03
print(groub.sum(axis=1, skipna=True)) # group and sum, but not the right result
#print(data.groupby(['date']).sum(axis=0, skipna=False))
load_data('public', 'zeitreihe')
如果
Date
是列的第一个聚合和,然后是每个axis=1
的sum
:或者通过
Date
列创建index
,然后对所有行和每个索引的最后一个总和(每个索引的总和):如果
Date
是索引,则上面的解决方案是simplify:相关问题 更多 >
编程相关推荐