简体   繁体   English

需要为 Panda 数据框打印一个新列

[英]Need to print a new column for Panda data frame

I am using the following code to print ratio by applying a function, but am getting the following errors.我通过应用 function 使用以下代码打印比率,但出现以下错误。

Code代码

import investpy
import pandas as pd
import numpy as np
import sys

def main(stock1_name, stock2_name):
    stock1 = investpy.get_stock_historical_data(stock=stock1_name,country='india', from_date='01/01/2020',to_date='08/03/2021')
    stock2 = investpy.get_stock_historical_data(stock=stock2_name,country='india', from_date='01/01/2020',to_date='08/03/2021')
    new_df = pd.merge(stock1, stock2, on='Date')
    new_df = new_df.drop(['Open_x', 'High_x', 'Low_x', 'Volume_x', 'Currency_x', 'Low_y','Volume_y', 'Currency_y', 'Open_y', 'High_y'], axis = 1)
    new_df['ratio'] = np.log10(new_df['Close_x']/new_df['Close_y'])
    return new_df
    x = main("IOC","HPCL")
print(x)

Error错误

NameError                                 Traceback (most recent call last)
<ipython-input-2-c17535375449> in <module>
     12     return new_df
     13     x = main("IOC","HPCL")
---> 14 print(x)

NameError: name 'x' is not defined
  1. You are calling x = main("IOC","HPCL") inside the function main您在 function main内部调用x = main("IOC","HPCL")
  2. This makes x defined only inside the scope of the function main这使得x仅在 function main的 scope 内部定义
  3. When you call print(x) outside function main the interpreter throws error, as it should, that x is not defined当您在 function main之外调用 print(x) 时,解释器会抛出错误,即x未定义

Does this correction solve the issue:此更正是否解决了问题:

import investpy
import pandas as pd
import numpy as np
import sys

def main(stock1_name, stock2_name):
    stock1 = investpy.get_stock_historical_data(stock=stock1_name,country='india', from_date='01/01/2020',to_date='08/03/2021')
    stock2 = investpy.get_stock_historical_data(stock=stock2_name,country='india', from_date='01/01/2020',to_date='08/03/2021')
    new_df = pd.merge(stock1, stock2, on='Date')
    new_df = new_df.drop(['Open_x', 'High_x', 'Low_x', 'Volume_x', 'Currency_x', 'Low_y','Volume_y', 'Currency_y', 'Open_y', 'High_y'], axis = 1)
    new_df['ratio'] = np.log10(new_df['Close_x']/new_df['Close_y'])
    return new_df

x = main("IOC","HPCL") # Edit moving this line outside the function main()
print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM