python - Dataframe manipulation, something with groupby, probably :/ -
need dataframe transformation. have
df = pd.dataframe({'c' : [1, 2, 1, 1, 2, 2, 1], 'd' : [1, 2, 13, 4, 5, 9, 10]}) df = df.sort('c') => c d 0 1 1 1 1 13 2 1 4 3 1 10 4 2 2 5 2 5 6 2 9
and get
f1 f2 f3 f4 1 1 13 4 10 2 2 5 9 nan
currently, loop on everything, on large dataframe, it's slow.
thanks
you adding new f column , calling pivot
:
>>> df["f"] = "f" + (df.groupby("c").cumcount() + 1).astype(str) >>> d2 = df.pivot(index="c", columns="f", values="d") >>> d2 f f1 f2 f3 f4 c 1 1 13 4 10 2 2 5 9 nan
the f , c there index , column names; if want rid of set them none.
>>> d2.index.name = none >>> d2.columns.name = none >>> d2 f1 f2 f3 f4 1 1 13 4 10 2 2 5 9 nan
Comments
Post a Comment