我使用的大熊貓,並創造了2個透視表,然後使用下面的代碼交錯他們進入1個數據幀:添加計算列
df_sales = pd.read_sql_query(sales_query, cnxn, params=[report_start, end_mtd, whse])
print('executing sales sql for warehouse : ' + whse)
df_sales['PERIOD'] = (((df_sales['INV_MONTH'].astype(str) + '/' + df_sales['INV_YEAR'].astype(str))))
df_sales = pd.pivot_table(df_sales, index=['REP', 'CUST_NO'], columns=['PERIOD'], values=['SALES'], fill_value=0)
df_profit = pd.read_sql_query(profit_query, cnxn, params=[report_start, end_mtd, whse])
print('executing profit sql for warehouse : ' + whse)
df_profit['PERIOD'] = (((df_profit['INV_MONTH'].astype(str) + '/' + df_profit['INV_YEAR'].astype(str))))
df_profit = pd.pivot_table(df_profit, index=['REP', 'CUST_NO'], columns=['PERIOD'], values=['PROFIT'], fill_value=0)
df = pd.concat([df_sales, df_profit], axis=1)[list(interleave([df_sales, df_profit]))]
我的輸出是這樣的:
SALES PROFIT SALES PROFIT
01/2017 01/2017 02/2017 02/2017
$96.01 $23.18 $7,347.66 $1,267.72
$600.00 $146.35 $600.00 $147.15
我想計算的df['MARGIN']
列添加到該表給出的輸出:
SALES PROFIT MARGIN SALES PROFIT MARGIN
01/2017 01/2017 02/2017 02/2017 02/2017 02/2017
$96.01 $23.18 24.14% $7,347.66 $1,267.72 17.25%
$600.00 $146.35 24.39% $600.00 $147.15 24.53%
我嘗試使用df['MARGIN'] = df['PROFIT']/df['SALES']
,但得到了一個錯誤:
ValueError: Wrong number of items passed 12, placement implies 1
假設這是錯誤的,因爲我已經包含在我的報告12期。
什麼爲df的'結果[ 'PROFIT']'/'DF [ 'SALES']'。似乎是一個數據類型的問題 –
@ A.Kot他們都是float64 – AlliDeacon
我認爲這個問題是重複的列名。 – Dark