Reputation: 83457
How can I apply function to each cell in a DataFrame that depends on the column name?
I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:
import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
returns:
b d e
Utah 1.624345 -0.611756 -0.528172
Ohio -1.072969 0.865408 -2.301539
Texas 1.744812 -0.761207 0.319039
Oregon -0.249370 1.462108 -2.060141
b d e
Utah 1.62 -0.61 -0.53
Ohio -1.07 0.87 -2.30
Texas 1.74 -0.76 0.32
Oregon -0.25 1.46 -2.06
Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.
I don't want to have to loop myself over each column, like:
def format2(cell_value, column_name):
return '{0}_{1:.2f}'.format(column_name, cell_value)
for column_name in frame.columns.values:
print('column_name: {0}'.format(column_name))
frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)
Returns:
b d e
Utah b_1.62 d_-0.61 e_-0.53
Ohio b_-1.07 d_0.87 e_-2.30
Texas b_1.74 d_-0.76 e_0.32
Oregon b_-0.25 d_1.46 e_-2.06
(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)
Upvotes: 4
Views: 4203
Reputation: 1190
why not:
>>> frame
b d e
Utah -0.579869 0.101039 -0.225319
Ohio -1.791191 -0.026241 -0.531509
Texas 0.785618 -1.422460 -0.740677
Oregon 1.302074 0.241523 0.860346
>>> frame['e'] = ['%.2f' % val for val in frame['e'].values]
>>> frame
b d e
Utah -0.579869 0.101039 -0.23
Ohio -1.791191 -0.026241 -0.53
Texas 0.785618 -1.422460 -0.74
Oregon 1.302074 0.241523 0.86
Upvotes: 1
Reputation: 863751
I bit improved another answer, axis=0
is by default so can be omit:
a = frame.apply(lambda x: x.apply(format2,args=(x.name)))
print (a)
b d e
Utah b_1.62 d_-0.61 e_-0.53
Ohio b_-1.07 d_0.87 e_-2.30
Texas b_1.74 d_-0.76 e_0.32
Oregon b_-0.25 d_1.46 e_-2.06
Upvotes: 4
Reputation: 19957
If you don't want to loop through the columns, you can do something like this:
frame.T.apply(lambda x: x.apply(format2,args=(x.name)), axis=1).T
Out[289]:
b d e
Utah b_0.90 d_-0.68 e_-0.12
Ohio b_-0.94 d_-0.27 e_0.53
Texas b_-0.69 d_-0.40 e_-0.69
Oregon b_-0.85 d_-0.67 e_-0.01
After transposing the df, the column names become index which can be referenced in apply function by using the .name attribute.
Upvotes: 2