1

I am trying to iterate through the rows of a dataframe and modify some values as I iterate. The dataframe looks like this:

     Time WindSpeed        SkyCover   Temp  DewPt   RH   Press  Precip
3   21:53      11       Light Snow   -1.7   -6.1  72%  1003.1       0
4   20:53    N 11    Mostly Cloudy   -2.2   -6.1  75%  1002.8       0
5   19:53    Calm    Mostly Cloudy   -2.8   -6.7  75%  1002.7       0
6   18:53    Calm         Overcast   -1.7   -6.7  69%  1002.4       0
7   17:53     N 5         Overcast   -1.7   -7.2  66%  1002.6       0
8   16:53    NE 8         Overcast   -1.1   -7.2  64%  1002.5       0
…

I have written the following loop to go through the dataframe and alter the windspeed column. This column is a vector when windspeed is greater than 1 KPH and a text value 'Calm' when below that threshold. I am wanting this loop to look at the column values row by row and if it is calm, put '1' in its place but if it is greater than one, remove the direction and keep only the scalar value.

for i in df.index:
    if df.at[i, 2] == 'Calm': 
        df.at[i, 2] = 1
    else:
        df.at[i, 2] = re.findall('[0-9]+', df.at[i, 2])[0]

As you can see in the above dataframe, this loop has worked on the first row of data but does not continue past that. I am not receiving any error messages as to why it is stopping after the first row.

3 Answers 3

3

Use apply:

df.WindSpeed = df.WindSpeed.apply(lambda x: 1 if x == 'Calm' else re.findall(r'[0-9]+',x)[0])
Sign up to request clarification or add additional context in comments.

Comments

1

Adding another way of doing it:

import numpy as np

df['WindSpeed'] = np.where(df['WindSpeed'] == 'Calm', '1', df['WindSpeed'].str.extract('(\d+)'))

Comments

0
df['WindSpeed']=df['WindSpeed'].apply(modify)

def modify(x):
       if x=='Calm' :
                    y=1;
       else: 
                    y=re.findall('[0-9]+',x)

       return y

1 Comment

meW's answer is better with lambda functions. Also sorry for bad formatting first answer here

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.