我有一个按日期索引的数据框
transactions_ind
Out[25]:
Ticker Transaction Number_of_units Price
Date
2012-10-11 ROG VX Equity Buy 12000 182.00000
2012-10-16 ROG VX Equity Sell -5000 184.70000
2012-11-16 ROG VX Equity Sell -5000 175.51580
2012-12-07 ROG VX Equity Buy 5000 184.90000
2012-12-11 ROG VX Equity Sell -3000 188.50000
2012-12-11 ROG VX Equity Reversal: Sell 3000 188.50000
2012-12-11 ROG VX Equity Sell -3000 188.50000
2012-12-11 ROG VX Equity Reversal: Sell 3000 188.50000
2012-12-11 ROG VX Equity Sell -3000 188.50000
2012-12-20 ROG VX Equity Sell -5000 185.80000
我想总结一下重复的索引值(2012-12-11)但仅限于“Number_of_units”列。
transactions_ind
Out[25]:
Ticker Transaction Number_of_units Price
Date
2012-10-11 ROG VX Equity Buy 12000 182.00000
2012-10-16 ROG VX Equity Sell -5000 184.70000
2012-11-16 ROG VX Equity Sell -5000 175.51580
2012-12-07 ROG VX Equity Buy 5000 184.90000
2012-12-11 ROG VX Equity Sell -3000 188.50000
2012-12-20 ROG VX Equity Sell -5000 185.80000
使用
transactions_ind.groupby(transactions_ind.index).sum()
删除“Ticker”和“Transaction”列,因为这些列填充了非数字值。另外,当我总结“Number_of_units”列时,我很想知道如何处理“事务”列中的不同字符串。希望大熊猫有一个单行班车。谢谢你的帮助!
答案 0 :(得分:8)
df = df.groupby(df.index).agg({'Ticker': 'first',
'Transaction': 'first',
'Number_of_units':sum,
'Price': 'first'})
#reorder columns
df = df[['Ticker','Transaction','Number_of_units','Price']]
print df
Ticker Transaction Number_of_units Price
Date
2012-10-11 ROG VX Equity Buy 12000 182.0000
2012-10-16 ROG VX Equity Sell -5000 184.7000
2012-11-16 ROG VX Equity Sell -5000 175.5158
2012-12-07 ROG VX Equity Buy 5000 184.9000
2012-12-11 ROG VX Equity Sell -3000 188.5000
2012-12-20 ROG VX Equity Sell -5000 185.8000
答案 1 :(得分:0)
如果(就像您的情况一样)您只有一个索引列,则接受的答案效果很好。如果您有一个 MultiIndex,不幸的是,它会将其减少为一个元组。这是恢复 MultiIndex 的方法:
import pandas as pd
index_names = df.index.names
df = df.groupby(df.index).agg({...})
df.index = pd.MultiIndex.from_tuples(df.index, names=index_names)