pandas - Append a tuple to a dataframe as a row -
i looking solution add rows dataframe. here data have : grouped object ( obtained grouping dataframe on month , year i.e in grouped object key [month,year] , value rows / dates in month , year).
i want extract month , year combinations , put in new dataframe. issue : when iterate on grouped object, month, row tuple, converted tuple list , added dataframe using thye append command. instead of getting added rows : 1 2014 2 2014 3 2014 got added in 1 column 0 1 1 2014 0 2 1 2014 0 3 1 2014 ...
i want store these values in new dataframe. here how want new dataframe : month year 1 2014 2 2014 3 2014
i tried converting tuple list , tried various other things pivoting. inputs helpful.
here sample code :
df=df.groupby(['month','year']) df = pd.dataframe() key, value in df: print "type of key is:",type(key) print "type of list(key) is:",type(list(key)) df = df.append(list(key)) print df
when groupby resulting multiindex available as:
in [11]: df = pd.dataframe([[1, 2014, 42], [1, 2014, 44], [2, 2014, 23]], columns=['month', 'year', 'val']) in [12]: df out[12]: month year val 0 1 2014 42 1 1 2014 44 2 2 2014 23 in [13]: g = df.groupby(['month', 'year']) in [14]: g.grouper.result_index out[14]: multiindex(levels=[[1, 2], [2014]], labels=[[0, 1], [0, 0]], names=['month', 'year']) often sufficient, , won't need dataframe. if do, 1 way following:
in [21]: pd.dataframe(index=g.grouper.result_index).reset_index() out[21]: month year 0 1 2014 1 2 2014 i thought there method this, can't recall it.
if want tuples can use .values or to_series:
in [31]: g.grouper.result_index.values out[31]: array([(1, 2014), (2, 2014)], dtype=object) in [32]: g.grouper.result_index.to_series() out[32]: month year 1 2014 (1, 2014) 2 2014 (2, 2014) dtype: object
Comments
Post a Comment