int“object is not iterable”,在索引i处出现

2024-06-16 10:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在数据帧“combined_sf2”中应用.mean函数,其中包含形状“43722行×62列”

我想从我的数据帧中为每一行计算一系列不同属性中某些值的平均值。然后生成名为“wkQtyEXTMean”的新属性/列,该属性/列将包含每行所选属性值范围的平均值

我尝试使用统计方法中的.mean函数创建以下函数:

    #function create to take the range of the selected attributes, if the sum is zero, so return the message 'thre is no mean', if not, calculate the mean
    
import statistics
    def wkQtyEXTMean(row):
        if (row['wk13QtyEXT']+row['wk12QtyEXT']) == 0:
            return 'No mean'
       else:
            return statistics.mean(row['wk13QtyEXT']+row['wk12QtyEXT'])

    #generating new column
    combined_sf2['wkQtyEXTMean'] = combined_sf2.apply(wkQtyEXTMean, axis=1)

但我得到了以下错误:

("'int' object is not iterable", 'occurred at index 43721')

预期结果enter image description here

有什么建议我该怎么办


Tags: the数据函数returnif属性isnot
2条回答

请找到最新的答案

# Online Python compiler (interpreter) to run Python online.

import pandas as pd
import statistics
# Creating the dataframe 
df = pd.DataFrame({"A":[12, 4, 5, None, 1],
                   "B":[7, 2, 54, 3, None],
                   "C":[20, 16, 11, 3, 8],
                   "D":[14, 3, None, 2, 6]})
  
# skip the Na values while finding the mean
print(df.mean(axis = 1, skipna = True))
te = df.mean(axis = 1, skipna = True)
print(statistics.mean(te))

13.25万美元

16.25万 2 23.333

3.2.666667

450万

数据类型:64

这就是答案。 10.1

老对话:

这是mean的语法

# Importing the statistics module
import statistics
  
# list of positive integer numbers
data1 = [1, 3, 4, 5, 7, 9, 2]
  
x = statistics.mean(data1)

现在你做错的是

return statistics.mean(row['wk13QtyEXT']+row['wk12QtyEXT']) is wrong
 
return statistics.mean(row) is right

尝试(你的方法):

import statistics

def wkQtyEXTMean(row):
    if row['wk13QtyEXT'] == 0 and row['wk12QtyEXT'] == 0:
        return 'No mean'
    return statistics.mean([row['wk13QtyEXT'], row['wk12QtyEXT']])

combined_sf2['wkQtyEXTMean'] = combined_sf2.apply(wkQtyEXTMean, axis=1)

或者没有statistics.mean

def wkQtyEXTMean(row):
    if row['wk13QtyEXT'] == 0 and row['wk12QtyEXT'] == 0:
        return 'No mean'
    return (row['wk13QtyEXT'] + row['wk12QtyEXT']) / 2

combined_sf2['wkQtyEXTMean'] = combined_sf2.apply(wkQtyEXTMean, axis=1)

或者没有apply

combined_sf2['wkQtyEXTMean'] = (combined_sf2['wk13QtyEXT']
                                + combined_sf2['wk12QtyEXT']) / 2
combined_sf2.loc[combined_sf2['wk13QtyEXT'].eq(0)
                 & combined_sf2['wk12QtyEXT'].eq(0), 'wkQtyEXTMean'] = 'No mean'

或者如果您已经在使用NumPy(np):

combined_sf2['wkQtyEXTMean'] = np.where(
            combined_sf2['wk13QtyEXT'].eq(0) & combined_sf2['wk12QtyEXT'].eq(0),
            'No mean',
            (combined_sf2['wk13QtyEXT'] + combined_sf2['wk12QtyEXT']) / 2
        )

相关问题 更多 >