pandas FOR循环-仅给出函数中第一次迭代的结果

bttbmeg0  于 2023-06-04  发布在  其他
关注(0)|答案(1)|浏览(151)

FOR循环只给出第一次迭代的结果,然后它停止,并且在查找pandas.dataframe的中位数时也不显示任何错误

def construct_frame(x):
    
    '''constructor function to get median of any data'''

    if x.shape[1]>=0:
        for i in range(1,(x.shape[1])):
            print(i)
            x_ser = x.iloc[:,i].sort_values(ignore_index=True)                 #sorting values in descending order

            x_ser_new= pd.Series(x_ser)

    #             print(x_ser)
    #             print(len(x_ser))
    #             print(type(x_ser))
    #             print(x_ser.dtypes)
    #             print(x_ser.shape[0])

            if len(x_ser_new)% 2==0:                                       #checking length of data if 'even'

                res = (x_ser_new[len(x_ser_new)//2]+ x_ser_new[(len(x_ser_new)//2)-1])/2   # nth column and (n-1)th column average
                return res 

            else:                                                      # if length of data is 'odd'

                res = x_ser_new[len(x_ser_new)//2]                             # nth column 

                return res


construct_frame(df)

结果应为10列,但仅显示第1列的中位数结果:
134.26

j2cgzkjk

j2cgzkjk1#

不要在循环中返回res,否则它会在第一次迭代时中断循环:

def construct_frame(x):
    
    '''constructor function to get median of any data'''

    median = {}  # HERE
    if x.shape[1]>=0:
        for i in range(1,(x.shape[1])):
            x_ser = x.iloc[:,i].sort_values(ignore_index=True)
            x_ser_new = pd.Series(x_ser)

            if len(x_ser_new)% 2==0:
                res = (x_ser_new[len(x_ser_new)//2]+ x_ser_new[(len(x_ser_new)//2)-1])/2
            else:
                res = x_ser_new[len(x_ser_new)//2]
            median[x_ser.name] = res  # HERE
    return pd.Series(median, name='median')  # HERE

输出:

>>> construct_frame(df)
Rank        2.0
Category      C
Name: median, dtype: object

更快的方法:

>>> df.iloc[:, 1:].quantile(0.5, numeric_only=False, interpolation='lower')
Rank        2.0
Category      C
Name: 0.5, dtype: object

相关问题