簡體   English   中英

迭代 Pandas DataFrame 的行作為字典

[英]Iteration over the rows of a Pandas DataFrame as dictionaries

我需要遍歷 Pandas 數據幀,以便將每一行作為帶有**kwargs的函數(實際上是類構造函數)的參數傳遞。 這意味着每一行都應該像一個字典,鍵是列名,值是每行對應的列名。

這有效,但它的表現非常糟糕:

import pandas as pd


def myfunc(**kwargs):
    try:
        area = kwargs.get('length', 0)* kwargs.get('width', 0)
        return area
    except TypeError:
        return 'Error : length and width should be int or float'


df = pd.DataFrame({'length':[1,2,3], 'width':[10, 20, 30]})

for i in range(len(df)):
    print myfunc(**df.iloc[i])

關於如何提高性能的任何建議? 我嘗試過使用df.iterrows()迭代,但出現以下錯誤:

類型錯誤:** 之后的 myfunc() 參數必須是映射,而不是元組

我也嘗試過df.itertuples()df.values ,但要么我遺漏了一些東西,要么意味着我必須將每個元組/ np.array 轉換為 pd.Series 或 dict ,這也會很慢。 我的限制是腳本必須使用 python 2.7 和 pandas 0.14.1。

一個干凈的選擇是這個:

for row_dict in df.to_dict(orient="records"):
    print(row_dict['column_name'])

你可以試試:

for k, row in df.iterrows():
    myfunc(**row)

這里k是數據幀索引,而row是一個字典,因此您可以使用以下命令訪問任何列: row["my_column_name"]

為此定義一個單獨的函數將是低效的,因為您正在應用逐行計算。 更有效的是計算一個新系列,然后迭代該系列:

df = pd.DataFrame({'length':[1,2,3,'test'], 'width':[10, 20, 30,'hello']})

df2 = df.iloc[:].apply(pd.to_numeric, errors='coerce')

error_str = 'Error : length and width should be int or float'
print(*(df2['length'] * df2['width']).fillna(error_str), sep='\n')

10.0
40.0
90.0
Error : length and width should be int or float

暫無
暫無

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

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