如何为Pandas DataFrame的索引列(v1股票代码列)添加表头?
Great question! The issue you're seeing is that your DataFrame's index (the stock symbols from your v1 list) doesn't have a name assigned. That's why the first column shows up without a header in your output. Let's walk through two straightforward ways to add the "v1" header you want:
Method 1: Set the Index Name When Creating the DataFrame
You can define the index name right when you initialize your DataFrame using pd.Index() to wrap your v1 list and assign a name to it. Here's how to modify that line of code:
# Replace this line: # df = pd.DataFrame(index = v1, columns = metric) # With this: df = pd.DataFrame(index=pd.Index(v1, name='v1'), columns=metric)
Method 2: Assign the Index Name After Data Scraping
If you prefer to keep your initial DataFrame setup as-is, you can add a single line after running your scraping function to name the index:
df = get_fundamental_data(df) # Add this line right here: df.index.name = 'v1' print(df)
Either of these methods will make your output match your desired result. Here's what the printed DataFrame will look like:
Sales Income v1 AAPL 365.82B 94.68B MSFT 184.90B 71.19B TSLA 53.82B 5.52B FB 112.33B 40.30B
Bonus: If You Want "v1" as a Regular Column (Not an Index)
If you'd rather have the stock symbols as a standard column instead of the index, you can use reset_index() to convert the index to a column and rename it:
df = df.reset_index().rename(columns={'index': 'v1'}) print(df)
This will give you output like this:
v1 Sales Income 0 AAPL 365.82B 94.68B 1 MSFT 184.90B 71.19B 2 TSLA 53.82B 5.52B 3 FB 112.33B 40.30B
Full Modified Code (Using Method 1)
Here's the complete code with the index name set during DataFrame creation:
import pandas as pd from bs4 import BeautifulSoup as bs import requests import numpy as np # For custom list of stocks, edit this list below, otherwise leave commented out v1 = ['AAPL','MSFT','TSLA','FB','BRK-B','TSM','NVDA','V','JNJ','JPM','WMT','PG','BAC','HD','BABA','TM','XOM','PFE','DIS','KO'] # Header required to scrape from Finviz headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Cookie': 'v2=1495343816.182.19.234.142', 'Accept-Encoding': 'gzip, deflate, sdch', 'Referer': "http://finviz.com/quote.ashx?t="} # This function is what is used to find the metric of interest and return it def fundamental_metric(soup, metric): return soup.find(text=metric).find_next(class_='snapshot-td2').text # This function iterates through the index of the data frame (stock_list) and uses the fundemental_metric functinon to find the metric on Finviz for that stock # Any stock in the list that cannot be scraped will return an error before moving on to the next stock def get_fundamental_data(df): for symbol in df.index: try: r = requests.get("http://finviz.com/quote.ashx?t="+ symbol.lower(),headers=headers) soup = bs(r.content,'html.parser') for m in df.columns: output = fundamental_metric(soup,m) df.loc[symbol,m] = output df.replace(['-'], np.NaN) except Exception as e: print (symbol, 'Not Found') print(e) return df # List of metrics to scrape # Before adding any metrics, ensure the metric being added is available on Finviz and the name is matched identically metric = ['Sales','Income'] # Set index name when creating DataFrame df = pd.DataFrame(index=pd.Index(v1, name='v1'), columns=metric) df = get_fundamental_data(df) print(df)
内容的提问来源于stack exchange,提问作者J R

