我有一个如下结构的数据集:
mydic = {'2017-9-11': {'Type1': [15, 115452.0, 3], 'Type2': [47, 176153.0, 4], 'Type3': [0, 0, 0]}, '2017-9-12': {'Type1': [26, 198223.0, 5], 'Type2': [39, 178610.0, 6], 'Type3': [0, 0, 0]}}
df = pd.DataFrame.from_dict(mydic, orient='index')我需要将列表中的值拆分为不同的列,并将它们按类型分组。我就是这样做的:
df_new = df[list(df)].unstack().apply(pd.Series)
df_new.head()它的作用是:
0 1 2
Type1 2017-9-11 15.0 115452.0 3.0
2017-9-12 26.0 198223.0 5.0
Type3 2017-9-11 0.0 0.0 0.0
2017-9-12 0.0 0.0 0.0
Type2 2017-9-11 47.0 176153.0 4.0但是,当我将这段代码应用于更大的现实数据集时,apply(pd.Series)似乎不起作用,我只得到了一列0,其中列出了如下所示的值:
0
Type1 2017-9-11 [15, 115452.0, 3]
2017-9-12 [26, 198223.0, 5]
Type2 2017-9-11 [47, 176153.0, 4]
2017-9-12 [39, 178610.0, 6]
Type3 2017-9-11 [0, 0, 0]有人能提出什么可能是错的吗?或者提出另一种解决方案?
发布于 2017-09-24 15:02:59
它认为更快的解决方案是DataFrame构造函数,参见timings
s = df.unstack()
df = pd.DataFrame(s.values.tolist(), index=s.index)
print (df)
0 1 2
Type1 2017-9-11 15 115452.0 3
2017-9-12 26 198223.0 5
Type2 2017-9-11 47 176153.0 4
2017-9-12 39 178610.0 6
Type3 2017-9-11 0 0.0 0
2017-9-12 0 0.0 0编辑:
如果值是字符串:
df = df.unstack().str.strip('[]').str.split(', ', expand=True).astype(float)
print (df)
0 1 2
Type1 2017-9-11 15.0 115452.0 3.0
2017-9-12 26.0 198223.0 5.0
Type2 2017-9-11 47.0 176153.0 4.0
2017-9-12 39.0 178610.0 6.0
Type3 2017-9-11 0.0 0.0 0.0
2017-9-12 0.0 0.0 0.0或者是可以将值转换为list的:
import ast
s = df.unstack().apply(ast.literal_eval)
df = pd.DataFrame(s.values.tolist(), index=s.index).astype(float)
print (df)
0 1 2
Type1 2017-9-11 15.0 115452.0 3.0
2017-9-12 26.0 198223.0 5.0
Type2 2017-9-11 47.0 176153.0 4.0
2017-9-12 39.0 178610.0 6.0
Type3 2017-9-11 0.0 0.0 0.0
2017-9-12 0.0 0.0 0.0发布于 2017-09-24 16:01:44
对于数据帧,指出要申请的女巫列。
df.unstack().to_frame()[0].apply(pd.Series)
Out[545]:
0 1 2
Type2 2017-9-11 47.0 176153.0 4.0
2017-9-12 39.0 178610.0 6.0
Type1 2017-9-11 15.0 115452.0 3.0
2017-9-12 26.0 198223.0 5.0
Type3 2017-9-11 0.0 0.0 0.0
2017-9-12 0.0 0.0 0.0中断:
df1=df.unstack().to_frame()
df1
Out[546]:
0
Type2 2017-9-11 [47, 176153.0, 4]
2017-9-12 [39, 178610.0, 6]
Type1 2017-9-11 [15, 115452.0, 3]
2017-9-12 [26, 198223.0, 5]
Type3 2017-9-11 [0, 0, 0]
2017-9-12 [0, 0, 0]然后做apply:
应用(pd.Series)
Out[550]:
0 1 2
Type2 2017-9-11 47.0 176153.0 4.0
2017-9-12 39.0 178610.0 6.0
Type1 2017-9-11 15.0 115452.0 3.0
2017-9-12 26.0 198223.0 5.0
Type3 2017-9-11 0.0 0.0 0.0
2017-9-12 0.0 0.0 0.0https://stackoverflow.com/questions/46391430
复制相似问题