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

Return position of columns with the same name in pandas

I would like to get the position of columns with the same name (that is column A).

DataFrame a:

A        B        A       C
text1    text3    text5   text7
text2    text4    text6   text8

I can get position of column A but how to get the position of the second column. There are multiple dataframe with different number of columns and position of A are not the same across the dataframes. Thank you.

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

for col in a.columns:   
        if col == 'A':
            indx1 = a.columns.get_loc(col)

        #if second column A 
            indx2 = a.columns.get_loc(col)


>Solution :

Your result can be easily achieved using np.where().

df = pd.DataFrame(
    data=[["text1", "text2", "text5", "text7"], ["text2", "text4", "text6", "text8"]],
    columns=["A", "B", "A", "D"],
)
np.where(df.columns == "A")[0]

Output:

array([0, 2], dtype=int64)
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