亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

Pandas:將函數應用于行,寫入新列

Pandas:將函數應用于行,寫入新列

素胚勾勒不出你 2021-07-15 14:11:16
將函數應用于數據框我目前有以下數據框:數據url                            visitorshttp://somedomain.com          200000http://someotherdomain.com     150000http://somenewdomain.com       11000對于數據框中的每一行,我喜歡將兩個函數應用于 url 列,然后將每個結果寫入兩個不同的列“meta”和“content”。職能:def metacrawler(url)    ...    return datadef contentcrawler(url)    ...    return data# Counterprogress = 0環形for index, row in data.iterrows():    print(str(progress)," out of ",str(len(data)))    print('Starting meta crawling.')    row['meta'] = metacrawler(row["url"])    print('Starting content crawling.')    row['content'] = contentcrawler(row["url"])    print('Complete.')    progress += 1但是,當我在幾次迭代后中止該過程時,我發現沒有數據寫入數據框中。也沒有創建列。我做錯了什么?
查看完整描述

1 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

您可以使用該.apply()功能的文檔與result_type='expand'


In [3]: df = pd.DataFrame({'one':[1,2,3,4], 'two':[5,6,7,8]})


In [4]: df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')

Out[4]:

    0   1

0   6   6

1   8   8

2  10  10

3  12  12


In [5]: df[['new', 'etc']] = df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')


In [6]: df

Out[6]:

   one  two  new  etc

0    1    5    6    6

1    2    6    8    8

2    3    7   10   10

3    4    8   12   12

編輯:如果要顯示進度,請單獨定義應用功能即


def func(row):

    print(row)

    return sum(row), sum(row)



In [3]: df = pd.DataFrame({'one':[1,2,3,4], 'two':[5,6,7,8]})


In [4]: df.apply(func), axis=1, result_type='expand')

Out[4]:

    0   1

0   6   6

1   8   8

2  10  10

3  12  12


In [5]: df[['new', 'etc']] = df.apply(lambda x: (sum(x), sum(x)), axis=1, result_type='expand')


In [6]: df

Out[6]:

   one  two  new  etc

0    1    5    6    6

1    2    6    8    8

2    3    7   10   10

3    4    8   12   12


查看完整回答
反對 回復 2021-07-21
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號