[英]For loop for formatting pandas dataframe
this is my first post to apologies for any mistakes in my question.这是我为我的问题中的任何错误道歉的第一篇文章。 I have only recently started to learn to code (since the beginning of quarantine lol.)
我最近才开始学习编码(自隔离开始以来,哈哈。)
I am trying to automate the manipulation of a pandas dataframe我正在尝试自动操作 pandas dataframe
# First I get the data for my etf
SOXX = web.DataReader('SOXX', 'yahoo', start, end)
# I now want to do the following to it
SOXX = pd.DataFrame(SOXX['Adj Close'])
SOXX.columns = ['SOXX']
I have tried for loops, cant get them to work.我试过for循环,不能让它们工作。 Tried defining a function, didn't work either!
尝试定义一个 function,也没有用!
What I would really like to do is, pass in a list of etf names, have it download all the data for each etf in the list and format each etf in the way I want in a single loop.我真正想做的是,传入一个etf名称列表,让它下载列表中每个etf的所有数据,并在一个循环中以我想要的方式格式化每个etf。
If I am looking to manipulate a column with some kind of function, I will use a pandas function called apply.如果我想用某种 function 操作列,我将使用名为 apply 的 pandas function。 See example below:
请参见下面的示例:
from yahoo_fin import stock_info as si
import pandas as pd
data = {'Symbol':['GOOG','AAPL'], }
# Create DataFrame
df = pd.DataFrame(data)
def applyFunction(row):
return si.get_live_price(row['Symbol'])
df['stockPrice'] = df.apply(applyFunction, axis=1) #axis=1 for column apply
Final table would look like决赛桌看起来像
Symbol | stockPrice
GOOG XXXX.XX
AAPL XXXX.XX
Hope that helps!希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.