簡體   English   中英

需要為 Panda 數據框打印一個新列

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

我通過應用 function 使用以下代碼打印比率,但出現以下錯誤。

代碼

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)

錯誤

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. 您在 function main內部調用x = main("IOC","HPCL")
  2. 這使得x僅在 function main的 scope 內部定義
  3. 當您在 function main之外調用 print(x) 時,解釋器會拋出錯誤,即x未定義

此更正是否解決了問題:

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