I have a few Pandas dataframes that I want to loop through at once to do some initial verification and debugging, but I can't figure out how to automate it. I've read a bunch of posts on here and various blogs of people trying to do something similar and the responses all tend towards "That's the wrong way to do that", but I haven't found anything that actually does what I'm looking for. In slightly-more-than-pseudocode, what I'm trying to do is:
for i in ('train', 'test', 'address', 'latlon'):
print('{}:'.format(i))
print(<i>.head()) ## what should <i> be?
In shell and Perl scripts it's as simple as encapsulating the variable name in {} (${i}
), but I can't find a Python equivalent. I've tried various permutations of format()
, but I keep getting AttributeError: 'str' object has no attribute 'head'
(I get the same error if I try just print(i.head())
). I've also tried using globals()
, but I get a key error on the first loop.
This is just for early-stage development and will get removed, so it doesn't have to be super clean, but it's an issue that I've ran into a few times now and it's really aggravating me.
EDIT: After some trial and error I got the below to work. Hopefully this will help someone in the future.
frames = dict({'train': train.head(), 'test': test.head(), 'address':address.head(), 'latlon': latlon.head()})
for i in frames.keys():
print('{}'.format(i))
print(frames[i])
I still don't understand how this is supposed to be an improvement over something like ${i} available in other languages, but it works.