[英]I am not able to correctly assign a value to a df row based on 3 conditions (checking values in 3 other columns)
[英]I want to attach one df column below another and assign row values based on other columns
我有一個使用下面的代碼構造的數據框。 我想將end和end_code列附加在start和start_code列下面。 如下所示,num和code的值可以設置為零。 我還在下面附上了我的預期輸出。
目前,我正在使用for循環遍歷每一行並在末尾手動分配它。 但是,該過程非常耗時。
謝謝
a['Code'] = ['A', 'B', 'A', 'C']
a['start'] = [pd.to_datetime('07:00'), pd.to_datetime('08:40'), pd.to_datetime('09:00'), pd.to_datetime('10:00')]
a['end'] = [pd.to_datetime('11:45'), pd.to_datetime('12:40'), pd.to_datetime('14:00'), pd.to_datetime('17:00')]
a['start_code'] = [1, 1, 1, 1]
a['end_code'] = [-1, -1, -1, -1]
Num Code start start_code
0 1 A 2019-07-30 07:00:00 1
1 2 B 2019-07-30 08:40:00 1
2 3 A 2019-07-30 09:00:00 1
3 4 C 2019-07-30 10:00:00 1
4 0 0 2019-07-30 11:45:00 -1
5 0 0 2019-07-30 12:40:00 -1
6 0 0 2019-07-30 14:00:00 -1
7 0 0 2019-07-30 17:00:00 -1
假設您有:
start_df
Out[1]:
Num Code start start_code
0 1 A 2019-07-30 07:00:00 1
1 2 B 2019-07-30 08:40:00 1
2 3 A 2019-07-30 09:00:00 1
3 4 C 2019-07-30 10:00:00 1
end_df
Out[2]:
end end_code
2019-07-30 11:45:00 -1
2019-07-30 12:40:00 -1
2019-07-30 14:00:00 -1
2019-07-30 17:00:00 -1
您可以簡單地串聯:
pd.concat([
start_df, end_df.rename(columns={'end':'start', 'end_code': 'start_code')
], axis=0, sort=False, ignore_index=True).fillna(0)
Out[3]:
Num Code start start_code
0 1 A 2019-07-30 07:00:00 1
1 2 B 2019-07-30 08:40:00 1
2 3 A 2019-07-30 09:00:00 1
3 4 C 2019-07-30 10:00:00 1
4 0 0 2019-07-30 11:45:00 -1
5 0 0 2019-07-30 12:40:00 -1
6 0 0 2019-07-30 14:00:00 -1
7 0 0 2019-07-30 17:00:00 -1
我相信melt
可能是您更好的選擇:
new_df = a.melt(id_vars='Code',
value_vars=['start','end'],
var_name='start_code',
value_name='start')
new_df['start_code'] = np.where(new_df['start_code'].eq('start'), 1, -1)
輸出:
Code start_code start
0 A 1 2019-07-30 07:00:00
1 B 1 2019-07-30 08:40:00
2 A 1 2019-07-30 09:00:00
3 C 1 2019-07-30 10:00:00
4 A -1 2019-07-30 11:45:00
5 B -1 2019-07-30 12:40:00
6 A -1 2019-07-30 14:00:00
7 C -1 2019-07-30 17:00:00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.