Apply Function To Each Cell In Dataframe That Depends On The Column Name In Pandas
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 na
Solution 1:
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
Solution 2:
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).TOut[289]:
bdeUtahb_0.90d_-0.68e_-0.12Ohiob_-0.94d_-0.27e_0.53Texasb_-0.69d_-0.40e_-0.69Oregonb_-0.85d_-0.67e_-0.01
After transposing the df, the column names become index which can be referenced in apply function by using the .name attribute.
Solution 3:
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
Post a Comment for "Apply Function To Each Cell In Dataframe That Depends On The Column Name In Pandas"