Home > Mobile >  Opening muli tiff files in a directory and applying all same steps
Opening muli tiff files in a directory and applying all same steps

Time:03-24

I have 12 tif images in /data directory and applying steps below for each:

  • Open a tif in data/ folder with gr.from_file
  • Send tif data to pandas with the code .to_pandas()
  • Change a column' name (value column = tifname) in pandas dataframe with the tif name
  • Change the name of the dataframe to be the same as the name of the tif.

The code given below is working one by one for each tif as well as I desired.

import georasters as gr
import numpy as np
import pandas as pd
import os
import glob

Altitude = './data/Altitude.tif'
Altitude = gr.from_file(Altitude)
Altitude = Altitude.to_pandas()
Altitude = Altitude.rename(columns={"value":"Altitude"})
Altitude

But it is non-useless to apply for each tif. So, I wrote a code given below:

# assign directory
directory = 'data/'
    
for filename in os.listdir('data/'):
    f = os.path.join(directory, filename)
    # checking if it is a file
    if os.path.isfile(f):
        a = gr.from_file(f)
        a = a.to_pandas()
        a = a.rename(columns={'value':'a'})
    print(a)

But it does not work as I desired. Code works for 12 tifs and saves only last tif's data as a. What changes do I need to make in the code to make it work the way I want?

CodePudding user response:

The next line is problematic in my view:

a = a.rename(columns={'value':'a'})

In each turn of your loop, the value will be the string 'a'. In your requirements, you need this to be the name of the file, without the .tif extension (Altitude when the file name is Altitude.tif)

As you always use 'a' as the value, it overwrites the previous result again and again, that's why you think it only works for the last tif.

Here's my suggestion, you should replace the aforementioned line of code with something like this:

#this line extracts the clean name from the filename (it removes the .tif extension)
cleanname = filename[0:-4]
#we now use it as a value
a = a.rename(columns={'value':cleanname})

CodePudding user response:

Finally, I found a solution given below. It is working on my issue. Maybe better, but for now at least it works.

# assign directory
directory = 'data/'
l=[]
for filename in os.listdir('data/'):
    f = os.path.join(directory, filename)
    cleanname = filename[0:-4]
    if os.path.isfile(f):
        a = gr.from_file(f)
        a = a.to_pandas()
        a = a.rename(columns={'value':cleanname})
        l.append(a)
    print(a)
  • Related