簡體   English   中英

在 Pandas 中添加新的 DataFrame 列不起作用

[英]Adding new DataFrame column in Pandas not working

所以我有一個 pandas DataFrame 包含一些來自 2001 年亞利桑那響尾蛇隊的擊球統計數據。 我對 Python/Pandas 很陌生,所以我試圖使用 lambda 函數添加幾列

PA_lambda = lambda row: row.AB + row.BB + row.HBP + row.SH + row.SF
OBP_lambda = lambda row: (row.H + row.BB + row.HBP) / (row.PA) if row.PA > 0 else 'NaN'
AVG_lambda = lambda row: row.H / row.AB if row.AB > 0 else 'NaN'

以后我想處理更多非常相似的數據,並且需要添加這些列,將來還會添加更多。 So I made a separate python module containing the functions, a list with each function and the column name that it should have, and a function to iterate through the list and add the columns onto the end of the DataFrame:

import pandas as pd 


PA_lambda = lambda row: row.AB + row.BB + row.HBP + row.SH + row.SF
OBP_lambda = lambda row: (row.H + row.BB + row.HBP) / (row.PA) if row.PA > 0 else 'NaN'
AVG_lambda = lambda row: row.H / row.AB if row.AB > 0 else 'NaN'

stat_functions = [['pa', PA_lambda], ['obp',OBP_lambda], ['avg', AVG_lambda]]
def format_df(df):
    for func in stat_functions:
        df['func[0]'] = df.apply(func[1], axis=1)

I'm not sure if I need the pandas module in there or not, but whenever I import the module into my Jupyter Notebook and try to call format_df, only the first function PA_lambda is run and it's saved into the DataFrame under the column label '功能'。 我認為使用列名和 function 本身創建一個列表會起作用,但是一旦它嘗試將 OBP_lambda 應用於 df 它就會返回錯誤

AttributeError: 'Series' object has no attribute 'PA'

抱歉,這有點長,這是我在這里的第一篇文章,但是如果您有解決方案,我非常渴望學習。

你不需要使用 apply ,你可以直接對 pandas 中的列進行這些操作:

df['pa'] = df['AB'] + df['BB'] + df['HBP'] + df['SH'] +df['SF']
df['obp'] = (df['H']+ df['BB']+df['HBP'])/df['PA']
df['avg'] = df['H']/df['AB']

您的 format_df(df) function 當前正在遍歷每個 function 並將每個結果的結果保存到同一列“func”,因為您的字符串格式不正確。 您需要使用“f-string”(在字符串前放一個 f)更新 function 的最后一行,以便在運行時對其進行格式化。

def format_df(df):
    for func in stat_functions:
        df[f'func[0]'] = df.apply(func[1], axis=1)

您需要做的是在 df 中創建新列時正確使用 func 項的 label 元素。

像這樣:

for func in stat_functions: 
    df[func[0]] = df.apply(func[1], axis=1)

請注意在 dataframe 中創建新列時,此代碼如何引用func[0]的值而不是字符串'func[0]'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM