LookIntoEast
LookIntoEast

Reputation: 8798

Python function pass-in variable to be used as name inside function

I'd like to change column name of dataframe:

def test(var):
    dic={'a': [5, 9],
     'b': [4, 1],
     'c': [2, 9]}

    df=pd.DataFrame(dic).transpose()
    df.columns=['aad',var_'k']
    return df
test('lalala')   

I would like second column name as var_'k'; that is, if I passed in lalala, the column name should be: lalala_k. But obviously there's syntax problem. What should I do? Thx

Upvotes: 0

Views: 39

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

This is just a normal string; you can build it up with concatenation or string functions. For example:

col = var + '_k'

or

col = '{}_k'.format(var)

Upvotes: 4

Related Questions