用熊猫删除空的数据框

时间:2018-06-26 23:09:04

标签: python regex python-3.x pandas dataframe

我编写了以下代码,以使用正则表达式请求页面,并查找类似于利率的字符串。整个代码有效;但是,它正在创建多个空数据帧,而我无法获得删除空帧以清理输出的代码。我一直在尝试使用.dropna,.drop和.empty尝试弃用数据框,但输出保持不变,并使用我已有的信息继续打印空的数据框。有没有一种我不知道的方法可以摆脱这些空框架。代码和输出如下:

plcompetitors = ['https://www.lendingclub.com/loans/personal-loans',
                'https://www.marcus.com/us/en/personal-loans',
                'https://www.discover.com/personal-loans/']

#cycle through links in array until it finds APR rates/fixed or variable using regex
for link in plcompetitors:
    cdate = datetime.date.today()
    l = r.get(link)
    l.encoding = 'utf-8'
    data = l.text
    soup = bs(data, 'html.parser')
    paragraph = soup.find_all(text=re.compile('[0-9]%'))
    for n in paragraph:
        matches = []
        matches.extend(re.findall('(?i)\d+(?:\.\d+)?%\s*(?:to|-)\s*\d+(?:\.\d+)?%', n.string))
        sint = pd.Series(matches)
        qdate = pd.Series([datetime.datetime.now()]*len(sint))
        slink = pd.Series([link]*len(sint))
        df = pd.concat([qdate,sint,slink],axis=1)
        df.columns = ['Date','Interest Rate', 'URL']
        print(df)

输出:

  ...
0 ...
1 ...

[2 rows x 3 columns]
 ...
0 ...

[1 rows x 3 columns]
 ...
0 ...
1 ...
2 ...
3 ...

[4 rows x 3 columns]
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
  ...
0 ...

[1 rows x 3 columns]
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []
Empty DataFrame
Columns: [Date, Interest Rate, URL]
Index: []

2 个答案:

答案 0 :(得分:3)

您怎么不打印/使用空的呢?

if df.empty:
  continue

if not df.empty:
  print(df)

答案 1 :(得分:0)

if df.dropna(how='all').empty:
    continue
根据{{​​3}}的

,仅包含nans的df将为.empty返回False,因此如果很重要,请首先使用dropna。如果NaN过多,则可以使用“ any”;如果所有NaN(可能是您想要的),仅希望删除行/列,则可以使用“ all”