Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在不等于零的不同行中选择最小值_Python_Pandas - Fatal编程技术网

Python 在不等于零的不同行中选择最小值

Python 在不等于零的不同行中选择最小值,python,pandas,Python,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

我有一个数据框:

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)
如何获得最小非零值

附言:我不想使用以下技巧,因为它会在以后引起头痛:

df = df.replace(0, np.NaN)

好的,我们选择列,得到非零值,然后找到min

(df[df[['apple', 'orange', 'peach', 'banana' ,'pear']] != 0]).min(axis = 1)
你得到

    year    apple   orange  peach   banana  pear    min_f
0   2010    11      45      0       13      22      11.0
1   2011    6       5       26      33      2       2.0
2   2012    34      3       56      23      0       3.0
3   2013    22      45      2       2       27      2.0
替代解决方案:

df.groupby(['year', 'country']).apply(lambda x: x[x > 0].min(axis=1))
返回:

year  country   
2010  China    0    11.0
2011  China    1     2.0
2012  China    2     3.0
2013  China    3     2.0
dtype: float64

这应该忽略使用pandas 0.19.2的非数值列。

我不需要写列名?如果整行都需要最小值,则不需要写。是的,但我有一些字符串值,在不同的列中。我只是在示例中没有使用它们。如果您有其他数值列,而不是用于查找最小值,您必须指定列。字符串不会受到影响。看社论你现在有足够的声望去投票了!祝贺通过投票选出你认为有用的答案来表达你的感激之情吧。
year  country   
2010  China    0    11.0
2011  China    1     2.0
2012  China    2     3.0
2013  China    3     2.0
dtype: float64