第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將函數(shù)應用于兩列Pandas數(shù)據(jù)幀

如何將函數(shù)應用于兩列Pandas數(shù)據(jù)幀

慕妹3146593 2019-07-31 14:50:33
如何將函數(shù)應用于兩列Pandas數(shù)據(jù)幀假設我有一個df列'ID', 'col_1', 'col_2'。我定義了一個函數(shù):f = lambda x, y : my_function_expression?,F(xiàn)在我想應用fto df的兩列'col_1', 'col_2'來逐元素地計算一個新列'col_3',有點像:df['col_3'] = df[['col_1','col_2']].apply(f)  # Pandas gives : TypeError: ('<lambda>() takes exactly 2 arguments (1 given)'怎么做 ?** 添加詳細示例如下 ***import pandas as pddf = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})mylist = ['a','b','c','d','e','f']def get_sublist(sta,end):    return mylist[sta:end+1]#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)# expect above to output df as below   ID  col_1  col_2            col_30  1      0      1       ['a', 'b']1  2      2      4  ['c', 'd', 'e']2  3      3      5  ['d', 'e', 'f']
查看完整描述

3 回答

?
慕妹3242003

TA貢獻1824條經(jīng)驗 獲得超6個贊

這是一個使用apply數(shù)據(jù)幀的示例,我正在調(diào)用它axis = 1。


注意區(qū)別在于,不是嘗試將兩個值傳遞給函數(shù)f,而是重寫函數(shù)以接受pandas Series對象,然后索引Series以獲取所需的值。


In [49]: df

Out[49]: 

          0         1

0  1.000000  0.000000

1 -0.494375  0.570994

2  1.000000  0.000000

3  1.876360 -0.229738

4  1.000000  0.000000


In [50]: def f(x):    

   ....:  return x[0] + x[1]  

   ....:  


In [51]: df.apply(f, axis=1) #passes a Series object, row-wise

Out[51]: 

0    1.000000

1    0.076619

2    1.000000

3    1.646622

4    1.000000

根據(jù)您的使用情況,創(chuàng)建一個pandas group對象,然后apply在該組上使用有時會很有幫助。


查看完整回答
反對 回復 2019-07-31
?
千萬里不及你

TA貢獻1784條經(jīng)驗 獲得超9個贊

一個簡單的解決方案是

df['col_3'] = df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)


查看完整回答
反對 回復 2019-07-31
?
梵蒂岡之花

TA貢獻1900條經(jīng)驗 獲得超5個贊

在熊貓中有一種干凈,單行的方式:


df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)

這允許f是具有多個輸入值的用戶定義函數(shù),并使用(安全)列名而不是(不安全)數(shù)字索引來訪問列。


數(shù)據(jù)示例(基于原始問題):


import pandas as pd


df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})

mylist = ['a', 'b', 'c', 'd', 'e', 'f']


def get_sublist(sta,end):

    return mylist[sta:end+1]


df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)

產(chǎn)量print(df):


  ID  col_1  col_2      col_3

0  1      0      1     [a, b]

1  2      2      4  [c, d, e]

2  3      3      5  [d, e, f]


查看完整回答
反對 回復 2019-07-31
  • 3 回答
  • 0 關注
  • 656 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號