I have a pandas dataframe which I'd like to print out with a special format:
df = pd.DataFrame({'A': [1, 5, 3], 'B': [90, 74, 180], 'C': ["aabb","bbcc", "ccdd"]})
The required output is:
For x1, referenced by aabb, the address is 0x5a
For x5, referenced by bbcc, the address is 0x4a
For x3, referenced by aabb, the address is 0xb4
i.e. something like -
print('For x%i, referenced by %s, the address is %x' % (df.A, df.C, df.B)`
Concatenating the columns as strings does not work -
print('For' + df.A + df.C + df.B)
I can easily do it using iterrows
. Is there a better way?
You can apply
along axis=1
using format
with an appropriate format string. Make sure to use dictionary unpacking within a lambda to get it done.
sfmt = 'For x{A}, referenced by {C}, the address is {B:#04x}'.format
df.apply(lambda x: sfmt(**x), 1)
0 For x1, referenced by aabb, the address is 0x5a
1 For x5, referenced by bbcc, the address is 0x4a
2 For x3, referenced by ccdd, the address is 0xb4
dtype: object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With