我有一个数据框架:
custid day freq
346782 1 0
346782 0 1
346782 1 2
346783 0 0
346783 0 1
346783 0 2但出于机器学习的目的,我想将其半转置为:
346782 1 0 0 1 1 2
346783 0 0 0 1 0 2你知道,这样custID只出现一次,所有相关的特性都在它前面的一行中。
我尝试过各种方法,例如:
df1 = pd.melt(newdf, id_vars=['0']).drop('variable', axis=1).sort_values(0)我怎样才能完成这个转换呢?
发布于 2018-02-06 12:42:10
我在这里用的是stack,你也可以试试melt
s=df.set_index('custid').stack()
s.index=pd.MultiIndex.from_arrays([s.index.get_level_values(level=0),s.groupby(level=0).cumcount()])
s.unstack()
Out[843]:
0 1 2 3 4 5
custid
346782 1 0 0 1 1 2
346783 0 0 0 1 0 2发布于 2018-02-06 13:13:14
您也可以尝试使用numpy.ravel。
df.groupby("custid").apply(lambda x: x[["day", "freq"]].values.ravel())
custid
346782 [1, 0, 0, 1, 1, 2]
346783 [0, 0, 0, 1, 0, 2]
dtype: object
pd.DataFrame(
df.groupby("custid").apply(lambda x: x[["day", "freq"]].values.ravel()).to_dict()
).T
0 1 2 3 4 5
346782 1 0 0 1 1 2
346783 0 0 0 1 0 2发布于 2018-02-06 13:22:13
使用
In [192]: pd.DataFrame.from_dict(
{k: x[['day', 'freq']].values.flatten() for k, x in df.groupby('custid')},
orient='index')
Out[192]:
0 1 2 3 4 5
346782 1 0 0 1 1 2
346783 0 0 0 1 0 2https://stackoverflow.com/questions/48635520
复制相似问题