簡體   English   中英

熊貓將功能應用於列的第二行

[英]Pandas apply function to every second row of column

我試圖在行之間的數值插值后更改第二行上的文本。

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

嘗試將此更改應用於第二個圖章行(即冒號之間為30而不是00)-str列

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

改變字符串的功能

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

我嘗試了以下方法:

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

但出現錯誤:AttributeError:'DataFrame'對象沒有屬性'rows'

當我嘗試:

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

AttributeError:“ str”對象沒有屬性“ name”

有任何想法嗎?

使用timedelta代替str

熊貓的優勢在於矢量化功能。 在這里,您可以使用timedelta來數字表示時間。 如果數據如您的示例所示,即秒始終為零,則可以按小時進行累加並增加30分鍾。 然后有條件地將此系列分配給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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM