【问题标题】:Split a long row into multiple rows将一长行拆分为多行
【发布时间】:2019-07-17 03:56:43
【问题描述】:

第一次发布 - 感谢任何反馈。 python 中的新用户试图获得一个从 AAA 获取国家天然气价格的刮刀。问题出现在如何将 numpy 转换为 pandas 以保留行 - 到目前为止,它正在转换为 DF 并将所有数据放在一行中。

import requests
import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://gasprices.aaa.com'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}  # This is chrome, you can set whatever browser you like
result = requests.get(url,headers = headers)

data = []
src = result.content
soup = BeautifulSoup(src,'lxml') #passing source variable into bs class to create an object
rows = soup.findAll("table", {"class": "table-mob"}) #parse box info
headers = []

for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele])

for row in rows:
    headers = row.find_all('th')
    headers = [ele.text.strip() for ele in headers]
    headers.append([ele for ele in headers if ele])


data = np.array(data)
df = pd.DataFrame(data)
print(df)

电流输出: enter image description here

目标是这样:

Current Avg.    $2.79   $3.11   $3.36   $3.01   $2.45                  
Yesterday Avg.  $2.79   $3.11   $3.36   $3.01   $2.45 
Week Ago Avg.   $2.75   $3.07   $3.32   $3.00   $2.42 
Month Ago Avg.  $2.69   $3.03   $3.28   $3.02   $2.33 
Year Ago Avg.   $2.87   $3.17   $3.42   $3.17   $2.43

【问题讨论】:

  • 数据看起来如何?你能发布一个样本吗?链接 https://gasprices.aaa.com 似乎不是 API 或 CSV
  • 程序的第一部分是来自 gasprices.aaa.com 的爬虫。查看当前输出图片了解 DF 到 CSV 的样子

标签: python-3.x pandas numpy


【解决方案1】:

np.reshape

  • np.reshape 将 df 中的值转换为 6 x 5 数组,首先向下展开。
  • idx, *dat 将结果数组中的第一行解压缩为名称 idx,并将其余行解压缩到名称为 dat 的列表中。 Variable Unpacking

idx, *dat = np.reshape(df.to_numpy(), (6, -1), order='F')
pd.DataFrame(dat, columns=idx).T

                     0       1       2       3       4
Current Avg.    $2.793  $3.107  $3.362  $3.010  $2.449
Yesterday Avg.  $2.792  $3.105  $3.360  $3.010  $2.449
Week Ago Avg.   $2.749  $3.068  $3.321  $3.004  $2.417
Month Ago Avg.  $2.689  $3.027  $3.280  $3.018  $2.332
Year Ago Avg.   $2.871  $3.167  $3.416  $3.168  $2.432

同样

idx, *dat = np.reshape(df.to_numpy(), (6, -1), order='F')
pd.DataFrame(dict(zip(idx, dat))).T

如果df.to_numpy 不起作用,请尝试:

idx, *dat = np.reshape(df.values, (6, -1), order='F')
pd.DataFrame(dict(zip(idx, dat))).T

【讨论】:

  • TypeError: 'numpy.ndarray' 对象不可调用
  • 您使用的是什么版本的熊猫? pd.__version__
  • Python 3.6.0 |Anaconda 4.3.0 pd.version.0.19.2
  • @PashBab 我已经更新了帖子。我认为这会奏效。如果没有,那么更险恶的事情正在发生。就像你可能已经覆盖了pd.DataFrame 或np.reshape
  • 成功了!介意将有关您的答案的文献联系起来-我不完全理解。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多