1

I am trying to create a dataframe by using the string that I pass as python function attribute. The string is used to feed parameters to scrape some data into a dataframe. I want to rename the dataframe using the string and also rename one of the column names with the string. I am attaching the code below in case it is not clear what I want.

def stock(tick):
    tick=tick.upper()
    tick, metadata=ts.get_daily(symbol=tick, outputsize='full')
    tick['date']=tick.index
    tick.index.name='index'
    tick=tick[['date', '4. close']]
    tick.columns=['date', 'tick_close']
    tick.sort_values('date', inplace=True)
    tick.drop_duplicates(subset='date', keep='first', inplace=True)
    return tick
GLD=stock('GLD')

In the code above, I want the dataframe to be renamed from tick to GLD and rename the column tick_close to GLD_close. I need to do all this by simply passing "GLD" to the function.

rmrm
  • 13
  • 5
  • What do you mean by "rename", exactly? – Karl Knechtel Jan 27 '20 at 06:20
  • Basically, I am passing a string as a function argument, now I want to use that string as the name of a column. The column is originally names as 'tick_close'. I am passing the string 'GLD' to the function. I now want to rename the column from 'tick_close' to 'GLD' – rmrm Jan 27 '20 at 23:20

1 Answers1

1

Not sure to understand your goal, but to rename a dataframes, But if you want to use 'GLD' to create a variable GLD, I'm afraid than it's not possible according to comment in Dynamically set local variable

Nota: the name of a variable define in def stock (tick) is only used in this function as you call a new variable named GLD during GLD=stock('GLD') so in the def function you can call variable as you want without impact after run GLD=stock('GLD')

you can do a copy of the dataframe using pandas:

GLD=tick.copy()

To change name of a column, you can do like that:

def stock(tick) :
   ... 
   #assuming you did the copy of the dataframe before. 
   GLD.columns=['date', f'{tick}_close']
   ... 
Renaud
  • 2,709
  • 2
  • 9
  • 24