简体   繁体   中英

Pandas apply function to every second row of column

I am trying to alter the text on every second row after interpolation the numeric values between rows.

    stamp     value
0   00:00:00  2
1   00:00:00  3
2   01:00:00  5

trying to apply this change to every second stamp row (ie 30 instead of 00 between colons) - str column

    stamp     value
0   00:00:00  2
1   00:30:00  3
2   01:00:00  5

function to change string

def time_vals(row):
    #run only on odd rows (1/2 hr)
    if int(row.name) % 2 != 0:
        l, m, r = row.split(':')
        return l+":30:"+r

I have tried the following:

hh_weather['time'] =hh_weather[hh_weather.rows[::2]['time']].apply(time_vals(2))

but I get an error: AttributeError: 'DataFrame' object has no attribute 'rows'

and when I try:

hh_weather['time'] = hh_weather['time'].apply(time_vals)

AttributeError: 'str' object has no attribute 'name'

Any ideas?

Use timedelta instead of str

The strength of Pandas lies in vectorised functionality. Here you can use timedelta to represent times numerically. If data is as in your example, ie seconds are always zero, you can floor by hour and add 30 minutes. Then assign this series conditionally to df['stamp'] .

# convert to timedelta
df['stamp'] = pd.to_timedelta(df['stamp'])

# create series by flooring by hour, then adding 30 minutes
s = df['stamp'].dt.floor('h') + pd.Timedelta(minutes=30)

# assign new series conditional on index
df['stamp'] = np.where(df.index % 2, s, df['stamp'])

print(df)

     stamp  value
0 00:00:00      2
1 00:30:00      3
2 01:00:00      5
#convert string value to timedelta (better to work with time)
df['stamp']=pd.to_timedelta(df['stamp'])

#slicing only odd row's from `stamp` column and adding 30 minutes to all the odd row's
odd_df=pd.to_timedelta(df.loc[1::2,'stamp'])+pd.to_timedelta('30 min')

#updating new series (out_df) with the existing df, based on index.
df['stamp'].update(odd_df)

#print(df)
    stamp   value
0   00:00:00    2
1   00:30:00    3
2   01:00:00    5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM