def mean1(x):
return sum(x)/len(x)
df2['children'] = df2['children'].apply(mean1)
我得到的錯誤如下:- “int”物件不可迭代
我想我正確地應用了 Apply() 函式。但是還是報錯。
uj5u.com熱心網友回復:
你應該申請mean1列,而不是專案:
df2['children'] = mean1(df2['children'])
或者更好的是,使用 pandas 內置mean方法:
df2['children'] = df2['children'].mean()
uj5u.com熱心網友回復:
使用示例資料框
In [372]: df
Out[372]:
0 1 2 3
1 0 1 2 3
2 4 100 6 7
3 8 9 10 11
In [373]: df[1] # one column
Out[373]:
1 1
2 100
3 9
Name: 1, dtype: int64
和您的功能 - 修改以顯示x它得到了什么:
In [375]: def mean1(x):
...: print(x)
...: return sum(x)/len(x)
...:
In [376]: df[1].apply(mean1)
1
Traceback (most recent call last):
File "<ipython-input-376-e12f9dfea5ae>", line 1, in <module>
df[1].apply(mean1)
File "/usr/local/lib/python3.8/dist-packages/pandas/core/series.py", line 4357, in apply
return SeriesApply(self, func, convert_dtype, args, kwargs).apply()
File "/usr/local/lib/python3.8/dist-packages/pandas/core/apply.py", line 1043, in apply
return self.apply_standard()
File "/usr/local/lib/python3.8/dist-packages/pandas/core/apply.py", line 1099, in apply_standard
mapped = lib.map_infer(
File "pandas/_libs/lib.pyx", line 2859, in pandas._libs.lib.map_infer
File "<ipython-input-375-48efb527b53e>", line 3, in mean1
return sum(x)/len(x)
TypeError: 'int' object is not iterable
看到x是1,一個數字。Python 不能執行sum和lenon 1。錯誤不在apply,而是在您的函式中,該函式并未考慮單個數字。
你打算它做什么?取整列的平均值?或者每個單元格中陣列或串列的平均值?
In [378]: mean1(df[1])
1 1
2 100
3 9
Name: 1, dtype: int64
Out[378]: 36.666666666666664
apply 如果資料框列包含串列或陣列,您的函式將起作用
In [386]: df = pd.DataFrame([None,None,None],columns=['one'])
In [387]: df['one'] = [np.ones(5).tolist(),np.arange(4).tolist(),np.zeros(9).tol
...: ist()]
In [388]: df
Out[388]:
one
0 [1.0, 1.0, 1.0, 1.0, 1.0]
1 [0, 1, 2, 3]
2 [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
In [389]: df['one'].apply(mean1)
[1.0, 1.0, 1.0, 1.0, 1.0]
[0, 1, 2, 3]
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
Out[389]:
0 1.0
1 1.5
2 0.0
Name: one, dtype: float64
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/393329.html
下一篇:從熊貓列中的串列中獲取最大值
