透视Pandas框架并从其他框架中获取遗漏的值

rt4zxlrg  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(58)

有两种 Dataframe :

table1

id |  time |  status
-----------------------
1  | 10:00 | conn     | 
1  | 10:01 | disconn  | 
2  | 10:02 | conn     | 
2  | 10:03 | disconn  | 
3  | 10:04 | conn     | 

table2

id |  time |
------------
3  | 10:05 |

字符串
如果某个标识没有断开时间值,则从表2中取。如何得到所需的结果?

id | conn | disconn|
--------------------
1  | 10:00| 10:01  |
2  | 10:02| 10:03  |
3  | 10:04| 10:05  |

x759pob2

x759pob21#

你可以pivot,然后fillnamap

out = (table1.pivot(index='id', columns='status', values='time')
             .reset_index().rename_axis(columns=None)
      )

out['disconn'] = out['disconn'].fillna(out['id'].map(table2.set_index('id')['time']))

字符串
第二步的变体:

m = out['disconn'].isna()
out.loc[m, 'disconn'] = out.loc[m, 'id'].map(table2.set_index('id')['time'])


输出量:

id   conn disconn
0   1  10:00   10:01
1   2  10:02   10:03
2   3  10:04   10:05


如果您有重复的ID/状态:

out = (table1.assign(n=lambda d: d.groupby(['id', 'status']).cumcount())
             .pivot(index=['id', 'n'], columns='status', values='time')
             .reset_index().rename_axis(columns=None)
      )

相关问题