簡體   English   中英

Python將函數應用於DataFrame的每一行

[英]Python apply function to each row of DataFrame

我有兩列 DataFrame: TypeName 每個單元格中的值都是等長的列表,即我們有對(Type, Name) 我想要:

  1. Name Type
  2. 使用Name的值創建列Type

我當前的代碼是一個 for 循環:

for idx, row in df.iterrows():
    for t in list(set(row["Type"])):
        df.at[idx, t] = [row["Name"][i] for i in range(len(row["Name"])) if row["Type"][i] == t]

但它的工作速度很慢。 如何加快此代碼的速度?

編輯這是說明我想要獲得但以更快的方式獲得的代碼示例:

import pandas as pd
df = pd.DataFrame({"Type": [["1", "1", "2", "3"], ["2","3"]], "Name": [["A", "B", "C", "D"], ["E", "F"]]})

unique = list(set(row["Type"]))
for t in unique:
    df[t] = None
    df[t] = df[t].astype('object')

for idx, row in df.iterrows():
    for t in unique:
        df.at[idx, t] = [row["Name"][i] for i in range(len(row["Name"])) if row["Type"][i] == t]

在此處輸入圖像描述

您可以編寫一個函數my_function(param)然后執行以下操作:

df['type'] = df['name'].apply(lambda x: my_function(x))

使用 lambda 函數可能有更好的選擇,但我記得 lambda。 如果您發布原始數據的簡化模擬以及所需輸出的外觀,它可能會幫助您找到問題的最佳答案。 我不確定我是否理解你想要做什么。 文字分組應該使用Dataframes 的 groupby 方法來完成。

如果我理解正確,您的數據框看起來像這樣:

df = pd.DataFrame({'Name':['a,b,c','d,e,f,g'], 'Type':['3,3,2','1,2,2,1']}) 


Name    Type
0   a,b,c   3,3,2
1   d,e,f,g 1,2,2,1

其中元素是字符串列表。 從運行開始:

df['Name:Type'] = (df['Name']+":"+df['Type']).map(process)

使用:

def process(x):
    x_,y_ = x.split(':')
    x_ = x_.split(','); y_ = y_.split(',')
    s = zip(x_,y_)
    str_ = ','.join(':'.join(y) for y in s)
    return str_

然后你會得到:

在此處輸入圖像描述

這將問題減少到單個列。 最后生成所需的數據框:

l = ','.join(df['Name:Type'].to_list()).split(',')
pd.DataFrame([i.split(':') for i in l], columns=['Name','Type'])

給予: 在此處輸入圖像描述

是你想要的結果嗎? (如果沒有,那么在您的問題中添加所需輸出的示例):

res = df.explode(['Name','Type']).groupby('Type')['Name'].agg(list)

print(res)
'''
Type
1    [A, B]
2    [C, E]
3    [D, F]
Name: Name, dtype: object

UPD

df1 = df.apply(lambda x: pd.Series(x['Name'],x['Type']).groupby(level=0).agg(list).T,1)
res = pd.concat([df,df1],axis=1)

print(res)
'''
           Type          Name       1    2    3
0  [1, 1, 2, 3]  [A, B, C, D]  [A, B]  [C]  [D]
1        [2, 3]        [E, F]     NaN  [E]  [F]

暫無
暫無

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

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