Ant*_*gor 5 python pivot spread pandas
我在 Python 中缺少从长到宽的自发和轻松转换,反之亦然。想象一下,我有一个大而整洁的数据框,其中包含许多属性列和一个包含所有实际值的列,例如
PropA ... PropZ Value
green Saturn 400
green Venus 3
red Venus 2
.
.
Run Code Online (Sandbox Code Playgroud)
数据本身通过保持整洁而得到很好的处理。但有时我必须对某些属性执行一些操作(例如,比较蜜蜂红色和绿色蜜蜂(对于与其他属性相似的所有项目)可能很有趣)。因此,直接的方法是尽可能保持整洁,只弄乱我感兴趣的某些属性(PropA)。随后,我可以使用我想要的任何函数执行逐行映射,并且我可以创建一个包含函数输出的附加 PropA-Entry。
然而,在 Python 中保持所有其他属性的整洁并不像我习惯使用 R 时那么容易。原因是,所有非关键属性都通过我找到的所有 pd 方法提交给索引。如果我想保留更多的专栏,那就一团糟。
那么你如何处理这个问题。有没有其他巧妙的方法来处理这些类型的问题?
我自己写了一个传播方法,但它非常慢。也许,你对我如何改进有一些想法。
#the idea is to group by the remaining properties, which should be left in the long format.
#then i spread the small tidy data table for any group
@staticmethod
def spread(df, propcol, valcol):
def flip(data,pc,vc):
data = data.reset_index(drop=True)
return {data[pc][i]:[data[vc][i]] for i in range(0,len(data))}
#index columns are all which are not affected
indcols = list(df.columns)
indcols.remove(propcol)
indcols.remove(valcol)
tmpdf=pd.DataFrame()
for key, group in df.groupby(indcols):
dc1 = {a:[b] for (a,b) in zip(indcols,key)}
dc2 = flip(group,propcol,valcol)
tmpdf = pd.concat([tmpdf,pd.concat([pd.DataFrame(dc1),pd.DataFrame(dc2)],axis=1)])
return tmpdf.reset_index(drop = True)
Run Code Online (Sandbox Code Playgroud)
在提示的帮助下,我创建了一个更简单的版本。我对索引机制仍然有点困惑,但时间会帮助我更好地理解。
def spread(df, propcol, valcol):
indcol = list(df.columns.drop(valcol))
df = df.set_index(indcol).unstack(propcol).reset_index()
df.columns = [i[1] if i[0] == valcol else i[0] for i in df.columns]
return df
Run Code Online (Sandbox Code Playgroud)