1

I try to use new-style formatting to display the entry at a given/specified column:

np.random.seed(1234)
df = pd.DataFrame(np.random.randint(7, size=(2, 2)), columns=['a', 'b'])
c = df.iloc[0, :] # get row number 0
print("Here is {one[0]} and {two}".format(one=c, two=c['b'])) # Ok

But I'd like to do it as follows:

print("Here is {one['a']} and {two}".format(one=c, two=c['b'])) ## Unfortunately KeyError: "'a'"

Is it possible to do that and how?

2
  • Why would you like to do it as you proposed? What are you trying to achieve? Commented Feb 25, 2016 at 16:47
  • The point is it's easier to specify directly one column by name instead of remembering that column number 6 is the one that I'm interested in! Commented Feb 25, 2016 at 17:21

2 Answers 2

2

I think you can remove '' in one['a']:

print("Here is {one[a]} and {two}".format(one=c, two=c['b']))
Here is 3 and 6
Sign up to request clarification or add additional context in comments.

1 Comment

Neat! I would have never thought of removing the extra quotes in the format string!
1

You can use loc to get the value of column a.

print("Here is {one} and {two}".format(one=c.loc['a'], two=c['b']))
Here is 3 and 6

You can also do it this way.

df['sum'] = df.sum(axis=1)

n = 0  # Get the first row.    
>>> "{row[a]} and {row[b]} makes {row[sum]}".format(row=df.iloc[n, :])
'3 and 6 makes 9'

6 Comments

Hi @Alexander. Thanks but no, your answer doesn't address my question: it's just a variation on two=c['b'] while I just want to specify the correct column in the format string.
Accessing the data point is similar, the difference is that the data should go in the format() section and any formatting applied to it should go in the brackets, eg. {one: %.2f}. Although technically possible, you should not specify your data in the string itself. docs.python.org/2/library/string.html#formatstrings
Why shouldn't one not specify the data field in the string itself? The doc you linked to doesn't do this recommendation. I thought that the possibility of specifying data fields in the string is even one of the most interesting points of the new-style formatting.
You use either positional arguments (e.g. {0}, {2}, etc. or named arguments (e.g. {one}, {two}, etc). You then specify the formatting of that data, eg. ""Here is {one:.2f} and {two:%}". Here is PEP 3101 which explains in detail the rational for the change. python.org/dev/peps/pep-3101
I am not recommending the abandonment of compound field names. I am promoting "simple is better than complex", "beautiful is better than ugly" and "readability counts".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.