如何为动态列的Pandas DataFrame添加行求和列并替换指定列?
Got it, let's break this down simply since you're new to Python and dealing with dynamic column names that change based on the ticker. Here's exactly how you can adjust your search_rank DataFrame to remove the isPartial column and add the dynamic Rank column:
Step 1: Remove the isPartial column
The interest_over_time() method from pytrends always includes isPartial as the last column, so we can safely drop it by name without worrying about your dynamic columns:
# Drop the fixed isPartial column search_rank = search_rank.drop('isPartial', axis=1)
Step 2: Add the Rank column with row sums
Since your data columns (the ones with the trend values) are all the columns left after removing isPartial, we can use pandas' sum() method with axis=1 to calculate the row-wise total. This works no matter what your column names are (they'll update automatically with each ticker):
# Calculate Rank as the sum of all trend columns for each row search_rank['Rank'] = search_rank.sum(axis=1)
Full integrated code
Add these two lines right after you generate search_rank in your existing script:
import yfinance as yf from pytrends.request import TrendReq as tr ticker = "TER" pytrends = tr(hl='en-US', tz=360) # 获取股票信息 stock = yf.Ticker(ticker) i = stock.info stock_info = {'Ticker':ticker} stock_info.update(i) # 获取Google Trends排名 longName = stock_info.get('longName') shortName = stock_info.get('shortName').split(',')[0] keywords = [ticker, longName, shortName] pytrends.build_payload(keywords, timeframe='all') search_rank = pytrends.interest_over_time() # --- New code starts here --- # Drop isPartial column search_rank = search_rank.drop('isPartial', axis=1) # Add Rank column with row sums search_rank['Rank'] = search_rank.sum(axis=1) # --- New code ends here ---
This will give you exactly the output you want: the date index, your three dynamic trend columns, and a Rank column with the total of each row's values. Even if you change the ticker to something else (like "AAPL"), this code will still work perfectly without any changes to column names.
内容的提问来源于stack exchange,提问作者Dave

