import pandas as pddata = {'name': ['Jason','Molly','Tina','Jake','Amy','lisa','Fred'],'gender': ['m','f','m','m'],}df1 = pd.DataFrame(data,index = [1,2,3,4,5,6,7,8,9,10])
我想创建一个包含一些标准和一些自定义汇总统计信息df2的表.
df2 = df1.describe()df2.rename(index={'top':'mode'},inplace=True)df2.rename(index={'freq':'mode freq'},inplace=True)df2
DF2:
gender name count 10 10 unique 2 7 mode f Molly mode freq 7 3
我想为第二种模式向df2追加一行,为第二种模式的频率追加一行:
例:
gender name count 10 10 unique 2 7 mode f Molly mode freq 7 3 2nd mode m lisa 2nd freq 3 2
我发现你可以得到第二种模式&这样做的频率:
my_serIEsfor column in df1: my_serIEs=df1[column].value_counts()[1:2] print(my_serIEs)
但是如何将其附加到df2?
解决方法@H_301_44@ 有柜台from collections import Counterdef f(s): return pd.SerIEs(Counter(s).most_common(2)[1],['mode2','mode2 freq'])df1.describe().rename(dict(top='mode1',freq='mode1 freq')).append(df1.apply(f)) name gendercount 10 10unique 7 2mode1 Molly fmode1 freq 3 7mode2 lisa mmode2 freq 2 3
value_counts
没有Counter的同样的事情
def f(s): c = s.value_counts() return pd.SerIEs([s.iat[1],s.index[1]],freq='mode1 freq')).append(df1.apply(f))
Numpy位
def f(s): f,u = pd.factorize(s) c = np.bincount(f) i = np.argpartition(c,-2)[-2] return pd.SerIEs([u[i],c[i]],freq='mode1 freq')).append(df1.apply(f))总结
以上是内存溢出为你收集整理的Python,pandas:如何将一个系列附加到数据帧全部内容,希望文章能够帮你解决Python,pandas:如何将一个系列附加到数据帧所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)