Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an elegant way to iterate over index and one column of a pandas dataframe?

I’d like have a loop that iterates over both the index, and the entries in one specific column of a dataframe. I’ve found a solution that works, but I feel there should be something more elegant. Any suggestions?

Working example:

import pandas as pd
df = pd.DataFrame(index = [10, 20, 30])
df['A'] = [1, 2, 3]
df['B'] = [5, 7, 9]

# This is the part that feels like it could be more elegant
for i, v in zip(df.index, df['A']):
    print(i, v)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The dataframe entry has a dictionary interface for this purpose. You can do df['A'].items()

import pandas as pd
df = pd.DataFrame(index=[10, 20, 30])
df['A'] = [1, 2, 3]
df['B'] = [5, 7, 9]

for i, v in df['A'].items():
    print(i, v)
10 1
20 2
30 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading