0

I have sample data frame(real data set has 100+ columns):

df = 

12_longitude_1  12_latitude_1   14_longitude_2  14_latitude_2   15_longitude_3  15_latitude_3
            11             12               13             14               15            16
            11             12               13             14               15            16
            11             12               13             14               15            16

I need to access every column with the loop. So I got the answer here like:

pd_out = pd.DataFrame({'zone': [], 'number': []})
max_cols = 3 # or 337 in your "real" dataset
for num in range(1, max_cols + 1):
    curr_lon_name = "longitude_{}".format(num) #what should I do here
    curr_lat_name = "latitude_{}".format(num)  #what should I do here
    #some code here

Is there another method to access the columns?

2
  • 1
    for col_name, column_series in df.iteritems(): gets you every column. Commented Nov 4, 2019 at 20:55
  • or for i ,col in df.groupby(level=0,axis=1): Commented Nov 4, 2019 at 20:57

2 Answers 2

1

I'm not sure exactly what you're asking for when you say "access the columns". It might help to know what you want to do with the columns beyond "access" them.

If you want a pair of lists for longitude corresponding latitude, you can do this:

lon_names = [i for i in df.columns if "longitude" in i]
lat_names = [i.replace("longitude", "latitude") for i in lon_names]

# Check the output
for i in range(len(lon_names)):
    print("Longitude_column={}, Latitude_column={}".format(lon_names[i], lat_names[i]))

Note that this will not work if there are unmatched latitude/longitude columns. If that's the case, you'll need to filter some of the column names from those lists.

Sign up to request clarification or add additional context in comments.

Comments

0

you can iterate on the DataFrame columns:

By column name:

 for col_name in pd.columns:
        print(df[col_name])

Or

By iteritems() function - see here

Comments

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.