我有两个pandas数据帧,格式如下:
df_ts = pd.DataFrame([
[10, 20, 1, 'id1'],
[11, 22, 5, 'id1'],
[20, 54, 5, 'id2'],
[22, 53, 7, 'id2'],
[15, 24, 8, 'id1'],
[16, 25, 10, 'id1']
], columns = ['x', 'y', 'ts', 'id'])
df_statechange = pd.DataFrame([
['id1', 2, 'ok'],
['id2', 4, 'not ok'],
['id1', 9, 'not ok']
], columns = ['id', 'ts', 'state'])
我正在尝试将其转换为指定格式,例如:
df_out = pd.DataFrame([
[10, 20, 1, 'id1', None ],
[11, 22, 5, 'id1', 'ok' ],
[20, 54, 5, 'id2', 'not ok'],
[22, 53, 7, 'id2', 'not ok'],
[15, 24, 8, 'id1', 'ok' ],
[16, 25, 10, 'id1', 'not ok']
], columns = ['x', 'y', 'ts', 'id', 'state'])
我知道可以通过按id分组,然后迭代每一行并在出现时更改状态来实现迭代。有没有更可扩展的pandas内置方法来做到这一点?
df_statechange
和df_ts
与df_out
的关系,您能否再详细解释一下? - Phung Duy Phongmerge
之外,您还需要使用cut
。请参阅此线程以获取更多详细信息:http://stackoverflow.com/questions/42649224/pandas-alternate-way-to-add-new-column-with-lot-of-conditions-other-than-apply - arnold