这里总共有熊猫新手,所以请多多怜悯。 我有一个数据样本,上面粘贴了形状的年度条目:
{"Country":{"0":"Italy","1":"Italy","2":"Italy","3":"Italy","4":"Italy","5":"Italy","6":"Italy","7":"France","8":"France","9":"France","10":"France","11":"France","12":"France","13":"Spain","14":"Spain","15":"Spain","16":"Spain","17":"Spain","18":"Spain","19":"Spain"},"Year":{"0":2004,"1":2005,"2":2006,"3":2007,"4":2008,"5":2009,"6":2010,"7":2006,"8":2007,"9":2008,"10":2009,"11":2010,"12":2011,"13":2007,"14":2008,"15":2009,"16":2010,"17":2011,"18":2012,"19":2013},"Revenue":{"0":1000,"1":1200,"2":1300,"3":1400,"4":1450,"5":1300,"6":1200,"7":2200,"8":2100,"9":1900,"10":2300,"11":2400,"12":2500,"13":1150,"14":1230,"15":1300,"16":1200,"17":1050,"18":900,"19":950}}
我需要一种方法来仅过滤所有国家/地区的常见年份,例如2007、2008、2009和2010。
我认为我应该制定一个公式并将其应用,但是我似乎找不到自己的出路。
答案 0 :(得分:5)
使用两次nunique
:获得唯一国家的数量n
,然后过滤年份,仅将唯一国家的数量等于n
n = df.Country.nunique()
s = df.groupby('Year').Country.nunique().eq(n)
>>> print(s)
Year
2004 False
2005 False
2006 False
2007 True
2008 True
2009 True
2010 True
2011 False
2012 False
2013 False
Name: Country, dtype: bool
要获得年份,
>>> print(s[s].index)
[2007, 2008, 2009, 2010]
也可以使用set
intersection
>>> set.intersection(*df.groupby('Country').Year.agg(set))
{2007, 2008, 2009, 2010}
答案 1 :(得分:3)
选项1
pivot
+ dropna
df.pivot('Year', 'Country', 'Revenue').dropna().index
选项2
crosstab
+ all
u = pd.crosstab(df.Year, df.Country)
u[u.all(1)].index
两种产品:
Int64Index([2007, 2008, 2009, 2010], dtype='int64', name='Year')