簡體   English   中英

如何使用pandas庫將數據寫入excel文件?

[英]How to write data to an excel file using pandas library?

我是python和Pandas的新手。我正在嘗試從網站獲取一些數據並以表格格式將它們寫入excel文件。“獲取數據”部分有效,但我似乎無法將它們寫入excel文件。 我想寫的格式是我的每個值都應該以“time-data-data-data ...”格式轉到同一行。

這是一個python 3項目。我嘗試過大熊貓的“.T”技巧。

a = sites[k]
     r = requests.get(a)
     c = r.content
     soup = BeautifulSoup(c, "html.parser")
     all_code = soup.find_all("td", {"class": "right"})
     my_value[k] = all_code[0].text
     k += 1
 my_file = pandas.read_excel("data.xlsx")
 my_file_t = my_file.T
 my_file_t[datetime.datetime.now()] = [my_value[0], my_value[1], my_value[2], my_value[3], my_value[4], my_value[5],
                                       my_value[6], my_value[7], my_value[8]]
 my_file = my_file_t.T

我希望它寫入data.xlsx文件。但程序出錯。 錯誤是

  File "C:/Users/kayab/Desktop/Projects/WORK IN PROGRESS/borsa/catcher.py", line 25, in <module>
    my_value[6], my_value[7], my_value[8]]
  File "C:\Users\kayab\AppData\Roaming\Python\Python37\site-packages\pandas\core\frame.py", line 3370, in __setitem__
    self._set_item(key, value)
  File "C:\Users\kayab\AppData\Roaming\Python\Python37\site-packages\pandas\core\frame.py", line 3445, in _set_item
    value = self._sanitize_column(key, value)
  File "C:\Users\kayab\AppData\Roaming\Python\Python37\site-packages\pandas\core\frame.py", line 3630, in _sanitize_column
    value = sanitize_index(value, self.index, copy=False)
  File "C:\Users\kayab\AppData\Roaming\Python\Python37\site-packages\pandas\core\internals\construction.py", line 519, in sanitize_index
    raise ValueError('Length of values does not match length of index')
ValueError: Length of values does not match length of index

當您嘗試使用名為時間戳的選項卡實現到Excel工作表的所有鏈接

# Convert the list into dataframe
my_file = pd.Dataframe(my_value)

now = datetime.datetime.utcnow()
time_tab = now.strftime("%Y-%m-%d")

# Save the dataframe as an excel
my_file.to_excel('data.xlsx', sheet_name=time_tab)

但是,整個程序可以用更加pythonic的方式編寫。

site_url = sites[idx]
content_requested = requests.get(site_url)
content = content_requested.content
soup = BeautifulSoup(content, "html.parser")

# Beautiful Soup returns an iterator object for find_all
all_code = soup.find_all("td", {"class": "right"})

# Save all the URL's into an list
my_value = []
for code in all_code:
    my_value.append(code[0].text)

# Convert the list into dataframe
my_file = pd.Dataframe(my_value)

now = datetime.datetime.utcnow()
time_tab = now.strftime("%Y-%m-%d")

# Save the dataframe as an excel
my_file.to_excel('data.xlsx', sheet_name=time_tab)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM