Python 从多个URL导入表以创建单个数据帧和csv文件
从多个URL导入表,并希望创建单个数据帧,然后将其存储为csv文件。我正在努力从表中删除重复的描述,并且在创建后无法操作数据帧dfmaster 可能是Python 从多个URL导入表以创建单个数据帧和csv文件,python,pandas,dataframe,Python,Pandas,Dataframe,从多个URL导入表,并希望创建单个数据帧,然后将其存储为csv文件。我正在努力从表中删除重复的描述,并且在创建后无法操作数据帧dfmaster 可能是pd.read\u html作为列表而不是数据框导入 我尝试遍历传入的表并使用 for item in df: if item not in dfmaster: dfmaster.append(item) print(dfmaster) 但这似乎列出
pd.read\u html
作为列表而不是数据框导入
我尝试遍历传入的表并使用
for item in df:
if item not in dfmaster:
dfmaster.append(item)
print(dfmaster)
但这似乎列出了令人不快的重复争吵
我还尝试了在附加到dfmaster和df.drop[0]
producturls = ['https://www.interactivebrokers.com/en/index.php?f=2222&exch=ecbot&showcategories=FUTGRP',
'https://www.interactivebrokers.com/en/index.php?f=2222&exch=cfe&showcategories=FUTGRP',
'https://www.interactivebrokers.com/en/index.php?f=2222&exch=dtb&showcategories=FUTGRP&p=&cc=&limit=100&page=2'
]
dfmaster =[]
for url in producturls:
table = pd.read_html(url, index_col=None, header=None,)
df = table[2]
for item in df:
if item not in dfmaster:
dfmaster.append(item)
print(dfmaster)
dfmaster.to_csv('IB_tickers.csv')
输出应将网站中的所有表格数据缝合到一个数据框中,而无需重复说明标题,然后创建并存储为可读的csv文件
非常感谢您的关注。这应该适合您:
import pandas as pd
from tabulate import tabulate
producturls = ['https://www.interactivebrokers.com/en/index.php?f=2222&exch=ecbot&showcategories=FUTGRP',
'https://www.interactivebrokers.com/en/index.php?f=2222&exch=cfe&showcategories=FUTGRP',
'https://www.interactivebrokers.com/en/index.php?f=2222&exch=dtb&showcategories=FUTGRP&p=&cc=&limit=100&page=2'
]
df_list = []
for url in producturls:
table = pd.read_html(url, index_col=None, header=None,)
df = table[2]
df_list.append(df)
dfmaster = pd.concat(df_list, sort=False)
dfmaster = dfmaster.drop_duplicates().reset_index(drop=True)
print(tabulate(dfmaster.head(), headers='keys'))
dfmaster.to_csv('IB_tickers.csv')
结果:
IB Symbol Product Description Symbol Currency
(click link for more details)
-- ----------- ------------------------------------------------------- -------- ----------
0 AC Ethanol -CME EH USD
1 AIGCI Bloomberg Commodity Index AW USD
2 B1U 30-Year Deliverable Interest Rate Swap Futures B1U USD
3 DJUSRE Dow Jones US Real Estate Index RX USD
4 F1U 5-Year Deliverable Interest Rate Swap Futures F1U USD
如何定义
dfmaster
?可以使用pandas.concat连接任意数量的数据帧(包含在列表中)。请参阅:因此,在URL列表中循环,将每个数据帧附加到一个列表中,然后使用pandas.concat组合成单个数据帧。然后将数据帧导出到csvDo我需要定义dfmaster??我是否应该添加dfmaster=pd.DataFrameIan谢谢,但这不是我的代码所做的吗?pd.read_html返回一个数据帧,我将其附加到dfmaster。代码创建了一个对象,但它不在dataframe中。dfmaster是一个列表而不是数据帧@Ian正在建议true\u df=pd.concat(dfmaster)
。然后导出到csv:true\u df.to\u csv('file.csv')
Ian我已经尝试了一整天,我感到内疚,认为你和你的解决方案是理所当然的。非常感谢您这么多的工作,只需要安装制表。谢谢你,千万遍了@你已经做了所有的艰苦工作。tablate是一个方便的可视化数据帧的软件包。当心!