-1
def statistics(model):
    Data['model']=pd.DataFrame(data=np.array([np.amax(model),
                               ME(ts,model),MAE(ts,model),
                               MAPE(ts,model)]))
    print(Data)

statistics(moving_avg) #calling the function

#result
  STATS        model
0   MAX  2359.699429
1    ME     4.521675
2   MAE   348.487434
3  MAPE    48.352464

The above is my code in PYTHON to insert the statistics of different models into a common table named Data However, the column name of the table is displayed as 'model' and not 'moving_avg'. How do I make sure that I get proper column names?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Deba
  • 11
  • 4

1 Answers1

-1

You can give an additional argument, as mentioned in the comment, which I actually think is a good practice. But if you want to save some typing, you can also use __name__ method, such as

def statistics(model):
    Data[model.__name__]=pd.DataFrame(data=np.array([np.amax(model),
                               ME(ts,model),MAE(ts,model),
                               MAPE(ts,model)]))
    print(Data)

model.__name__ gives you a string of the name of the function model

print(moving_avg.__name__)
# -> moving_avg

Update

Some people mentioned the variable. Thanks for the kind reminding. A dirty solution is define a function with the same name which returns the variable. This is possible and not so difficult, since the variable name is known. For other types of object without __name__ method, this also works (only in simple situation!).

ax = [1,2,3]
def ax: return ax
print(ax.__name__)
# -> ax

However, I do not recommend to go too far on this direction. I do not think there is really a generic solution for all types of objects and in complex situations, all these attempts of playing around namespace can be risky. You may get something really unexpected. See the discussions here

How can I get the name of an object in Python?

englealuze
  • 1,445
  • 12
  • 19
  • What if model is not a function but a variable, an array. It will not work then and thats what the OP wants. – Vivek Kumar Feb 06 '18 at 08:43
  • @VivekKumar I think there is no simple generic solution for all types of objects. Since python objects can have no name or multiple names. There are already a lot discussions here https://stackoverflow.com/questions/1538342/how-can-i-get-the-name-of-an-object-in-python things becomes extremely tricky considering scopes and frames. That is why I think it is risky if we go too far along this direction for this specific question... – englealuze Feb 06 '18 at 09:28
  • Thats why I downvoted your answer because it does indeed takes the question in other direction. – Vivek Kumar Feb 06 '18 at 09:31
  • @VivekKumar Thanks for your explanation. In this sense, I totally agree with your downvote – englealuze Feb 06 '18 at 10:52
  • @Deba if you think the answer is helpful, please consider to accept it – englealuze Feb 09 '18 at 08:01