[英]I have a problem with applying my logic into python code
我是 pandas 的新手,我不知道如何將以下邏輯應用到 pandas 代碼中。 我能得到的所有幫助將不勝感激!
例如,在我的 dataframe 中有以下內容:
id uid action program time sleepTimes
1628 100 5 200 2020-05-20 2020-05-20
1629 100 1 200 2020-05-21 0
我希望 id 1629 的sleepTimes
列與 id 1628 的sleepTimes
列具有相同的值,因為它們具有相同的 uid 和程序。 我想將此應用於驗證相同條件的所有行。
對於一般的觀點,我想添加到sleepTimes
of action = 1
列中,當actions = 1
具有相同的uid
和program
of action = 5
= 5 時, sleepTimes
of action = 5
的值。 我怎么能這樣做,使用 python?
觀察:我的 dataframe 是使用 pandas 創建的。
謝謝!
編輯:這是我開始的代碼。
df['sleepTimes'] = np.where(df['action'] == 5, df['time'], 0)
uid = df.loc[df['action'] == 5, 'uid']
def mapping_time (df):
if (df['action'] == 1).all():
#compare and check if uid and program are equal to action 1 and action 5.
if df['uid'] == df['sleepTimes'] & df['program']:
df['sleepTimes'] = df.loc[df['action'] == 5, 'time']
elif (df['action'] == 3).all():
if(df['uid'] == uid):
df['sleepTimes'] = sleepTimes
else:
#it is action = 5
df['sleepTimes'] = df['time']
只需使用astype()
和replace()
方法:
df['sleepTimes']=df['sleepTimes'].astype(str).replace('0',np.NaN)
最后使用groupby()
方法和ffill()
方法:
df['sleepTimes']=df.groupby('uid')['sleepTimes'].ffill()
現在如果你打印df
你會得到你想要的 output
#output
id uid action program time sleepTimes
0 1628 100 5 200 2020-05-20 2020-05-20
1 1629 100 1 200 2020-05-21 2020-05-20
現在,如果您想對 'sleepTimes' 執行一些操作,請使用pd.to_datetime()
方法將其轉換為datetime[ns]
:
df['sleepTimes']=pd.to_datetime(df['sleepTimes'])
編輯:
df['sleepTimes']=df.groupby(['uid','program'])['sleepTimes'].ffill()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.