![](/img/trans.png)
[英]Applying a custom function on a Pandas series using groupby and pd.isnull
[英]Applying a custom function to pandas Series produces AttributeError
我想為 pandas 系列創建自定義摘要 function。
df["tmk"].min()
df["tmk"].max()
這行得通。
def min_max(x):
minimum = x.min()
maximum = x.max()
print(f'Min: {minimum} | Max: {maximum}')
df["tmk"].apply(lambda x: min_max(x))
AttributeError: 'float' object has no attribute 'min'
我想我在這里做錯了。 誰能幫我正確應用 function 嗎?
如果使用Series.apply
它按列的每個值循環。 錯誤意味着標量沒有min
和max
。
df = pd.DataFrame({
'tmk':[4,5,4,5,5,np.nan],
})
def min_max(x):
minimum = x.min()
maximum = x.max()
print(f'Min: {minimum} | Max: {maximum}')
您需要按Series.pipe
處理列的所有值:
df["tmk"].pipe(min_max)
或將系列傳遞給 function,就像在評論中提到的@AkshayNevrekar 一樣:
min_max(df["tmk"])
另一個想法是使用DataFrame.apply
- 為一列添加[]
DataFrame
:
df[["tmk"]].apply(min_max)
Min: 4.0 | Max: 5.0
另一種方法是使用Series.describe
或Series.agg
:
print (df['tmk'].describe())
count 5.000000
mean 4.600000
std 0.547723
min 4.000000
25% 4.000000
50% 5.000000
75% 5.000000
max 5.000000
Name: tmk, dtype: float64
print (df['tmk'].agg(['min', 'max']))
min 4.0
max 5.0
Name: tmk, dtype: float64
也可以像@Jon Clements 提到的那樣添加format
,謝謝:
print ('Min: {min} | Max: {max}'.format_map(df['tmk'].agg(['min', 'max'])))
Min: 4.0 | Max: 5.0
對於這種分析,只需使用系列描述方法。
如果你想在這里解釋你的錯誤,那就是。 這樣做:
df["tmk"].apply(lambda x: min_max(x))
您正在將 function 應用於系列中的每個值。 該值的類型為“float”。 python 中的浮點數沒有最大或最小方法。 相反,您可以使用:
df["tml"].min()
或者可能是內置 python 最小/最大,如:
min(df["tml"])
如果您只想獲取最小值和最大值,使用describe()
方法可能會更容易
import pandas as pd
import numpy as np
# fix seeds so we get the same numbers
np.random.seed(42)
a = np.random.normal(0, 1, 10)
np.random.seed(42)
b = np.random.uniform(0, 1, 10)
df = pd.DataFrame({"A": a, "B": b})
df.describe()
>>> A B
count 10.000000 10.000000
mean 0.448061 0.520137
std 0.723008 0.315866
min -0.469474 0.058084
25% -0.210169 0.210649
50% 0.519637 0.599887
75% 0.737498 0.726014
max 1.579213 0.950714
您可以從那里獲取最小值、最大值和其他指標
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.