小编Ale*_*lex的帖子

使用BeautifulSoup将表刮到数据框中

我正试图从硬币目录中删除数据.

一个页面.我需要将这些数据写入Dataframe

到目前为止,我有这个代码:

import bs4 as bs
import urllib.request
import pandas as pd

source = urllib.request.urlopen('http://www.gcoins.net/en/catalog/view/45518').read()
soup = bs.BeautifulSoup(source,'lxml')

table = soup.find('table', attrs={'class':'subs noBorders evenRows'})
table_rows = table.find_all('tr')

for tr in table_rows:
    td = tr.find_all('td')
    row = [tr.text for tr in td]
    print(row)                    # I need to save this data instead of printing it 
Run Code Online (Sandbox Code Playgroud)

它产生以下输出:

[]
['', '', '1882', '', '108,000', 'UNC', '—']
[' ', '', '1883', '', '786,000', 'UNC', '~ $3.99']
[' ', " \n\n\n\n\t\t\t\t\t\t\t$('subGraph55337').on('click', …
Run Code Online (Sandbox Code Playgroud)

beautifulsoup dataframe web-scraping pandas

7
推荐指数
3
解决办法
1万
查看次数

对Pandas数据帧使用apply函数

我正在尝试用大熊猫每月付款来模拟贷款.

信用列包含这是我从银行借款的金额.

借记列包含我祈祷,回到银行的钱数.

列应该包含哪些被留下支付给银行的金额.基本上它包含信用和借记列之间的减法结果).

我能够编写以下代码:

import pandas as pd

# This function returns the subtraction result of credit and debit
def f(x):
    return (x['credit'] - x['debit'])


df = pd.DataFrame({'credit': [1000, 0, 0, 500],
                   'debit': [0, 100, 200, 0]})

for i in df:
    df['total'] = df.apply(f, axis=1)

print(df)
Run Code Online (Sandbox Code Playgroud)

它有效(它从信用卡中扣除借方).但它不会在总列中保留结果.请参阅下面的实际和预期结果.

实际结果:

   credit  debit        total
0    1000      0         1000
1       0    100         -100
2       0    200         -200
3     500      0          500
Run Code Online (Sandbox Code Playgroud)

预期结果:

   credit  debit        total …
Run Code Online (Sandbox Code Playgroud)

python pandas

1
推荐指数
1
解决办法
47
查看次数

标签 统计

pandas ×2

beautifulsoup ×1

dataframe ×1

python ×1

web-scraping ×1