Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting an entire pandas dataframe as a string, row by row

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?

like image 521
carmi Avatar asked Jul 17 '17 05:07

carmi


1 Answers

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
like image 92
piRSquared Avatar answered Oct 11 '22 07:10

piRSquared