-1

In SAS by use of Macros I am able to rename various datasets according to the arguments passed in the macro, how can I achieve the same in Python? IT might be stupid question but I am a newbie, so any help is appreciated

  • Could you provide example what are you trying to achieve? What is your dataset? What is desired output? – Adrian Krupa Feb 22 '19 at 10:51
  • Say in SAS I have a macro and I can pass an argument in that macro to dynamically change the output names based on the macro. %macro dataread(yymm); *Called by macro LGD; %let colour_keep = %nrstr(%mend;); %if &yymm. = 1712 %then %do; proc sort data=GP&yymm._ out=&yymm._sorted_data Above is just a snippet of the code. How can I replicate similar dynamic renaming in python? – Prashant Tiwari Feb 22 '19 at 10:57
  • It's very hard to help without example data. Also please edit your question if you provide more information – Adrian Krupa Feb 22 '19 at 11:26
  • You would build yourself a custom Python function. – Reeza Feb 22 '19 at 15:50
  • Check out this thread: https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string – Tom Feb 25 '19 at 16:53

1 Answers1

0

Edit: Based on Tom's feedback, I re-read the question and revised the answer.

Your question if really broad. In short, yes, you can pass arguments to macros and you can use them to rename you existing data. For instance:

import pandas as pd

def main():
    my_df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
    rename('foo', my_df)

def rename(name, The_DF):
    globals()["%s" % name] = The_DF

if __name__=='__main__':
    main()

Will yield dataFrame called Foo. With so little information provided, this is the best I can provide you with.

Note that globals() is not the same as Global. Prior SO thread explains it. For basics in Python functions I recommend w3schools

pinegulf
  • 1,040
  • 10
  • 28
  • You are just using the value of the input string to generate another string. The question is how to use the value of the string as the NAME of some other object. – Tom Feb 25 '19 at 14:36
  • @Tom Rigth you are. Revisited the answer. – pinegulf Feb 26 '19 at 07:23