我有一个 Pandas 数据框:
year country apple orange peach banana pear export
2010 China 11 45 0 13 22 25
2011 China 6 5 26 33 2 44
2012 China 34 3 56 23 0 22
2013 China 22 45 2 2 27 14
我知道如何获得每年的最小值,例如:
df["min_f"] = df[['apple', 'orange', 'peach', 'banana' ,'pear']].min(axis=1)
如何获得最小非零值?
P.S:我不想使用以下技巧,因为以后会让人头疼:
df = df.replace(0, np.NaN)
最佳答案
icol = ['year', 'country']
f = lambda x: x != 0
mins = df.set_index(icol).stack().compress(f).groupby(level=[0, 1]).min()
df.join(mins.rename('min_f'), on=icol)
year country apple orange peach banana pear export min_f
0 2010 China 11 45 0 13 22 25 11
1 2011 China 6 5 26 33 2 44 2
2 2012 China 34 3 56 23 0 22 3
3 2013 China 22 45 2 2 27 14 2
关于python - 选择不等于零的不同 pandas 行中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478285/