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
1条答案
按热度按时间j2cgzkjk1#
不要在循环中返回
res
,否则它会在第一次迭代时中断循环:输出:
更快的方法: