给定一个数据帧
+----+-------+------+-----------+-----------+---------------+
| | Key | ID | Status1 | Status2 | OrderID |
|----+-------+------+-----------+-----------+---------------|
| 0 | 1 | A1 | False | True | 1234-USF-0025 |
| 1 | 1 | A1 | False | True | 1234-USF-0026 |
| 2 | 1 | A1 | False | True | 1234-USF-0027 |
| 3 | 2 | A1 | True | True | 1234-USF-0025 |
| 4 | 2 | A1 | True | True | 1234-USF-0026 |
| 5 | 2 | A1 | True | True | 1234-USF-0027 |
| 6 | 3 | A1 | Anything | True | 1234-USF-0025 |
| 7 | 3 | A1 | False | True | 1234-USF-0026 |
| 8 | 3 | A1 | False | Anything | 1234-USF-0027 |
| 9 | 4 | A2 | True | True | 1234-USF-0028 |
| 10 | 4 | A2 | True | True | 1234-USF-0029 |
| 11 | 4 | A2 | True | True | 1234-USF-0030 |
| 12 | 5 | A3 | True | True | 1234-USF-0031 |
| 13 | 5 | A3 | True | True | 1234-USF-0032 |
| 14 | 5 | A3 | True | True | 1234-USF-0033 |
| 15 | 6 | A4 | True | True | 1234-USF-0034 |
| 16 | 6 | A4 | True | True | 1234-USF-0035 |
| 17 | 6 | A4 | True | True | 1234-USF-0036 |
+----+-------+------+-----------+-----------+---------------+
如何转换为按ID
列出每个OrderID
,并基于每个Status
连接Key
。如果两个Stautses
都是真的,那么连接的Keys
应该放在TRUE
列中。如果其中一个是Flase
,Keys
应该放在FALSE
列中。如果其中一个(或两者)Status
不是True
或False
,则Key(s)
会连接到Other
列中
期望结果df
Order ID ID TRUE FALSE OTHER
1234-USF-0025 A1 2 1 3
1234-USF-0026 A1 2 1,3
1234-USF-0027 A1 2 1 3
1234-USF-0028 A2 4
1234-USF-0029 A2 4
1234-USF-0030 A2 4
1234-USF-0031 A3 5
1234-USF-0032 A3 5
1234-USF-0033 A3 5
1234-USF-0034 A4 6
1234-USF-0035 A4 6
1234-USF-0036 A4 6
我尝试过的
df = df.groupby(['OrderID','ID'])['Key'].apply(','.join).reset_index()
+----+---------------+------+-------+
| | OrderID | ID | Key |
|----+---------------+------+-------|
| 0 | 1234-USF-0025 | A1 | 1,2,3 |
| 1 | 1234-USF-0026 | A1 | 1,2,3 |
| 2 | 1234-USF-0027 | A1 | 1,2,3 |
| 3 | 1234-USF-0028 | A2 | 4 |
| 4 | 1234-USF-0029 | A2 | 4 |
| 5 | 1234-USF-0030 | A2 | 4 |
| 6 | 1234-USF-0031 | A3 | 5 |
| 7 | 1234-USF-0032 | A3 | 5 |
| 8 | 1234-USF-0033 | A3 | 5 |
| 9 | 1234-USF-0034 | A4 | 6 |
| 10 | 1234-USF-0035 | A4 | 6 |
| 11 | 1234-USF-0036 | A4 | 6 |
+----+---------------+------+-------+
上面的内容当然让我很接近,但我不知道如何将Keys
分解成各自的列(TRUE
、FALSE
和OTHER
)
注意事项
我以前将Key
列转换为字符串
Order IDs
可以为IDs
复制,但将具有不同的Keys
这是一个可行的解决方案,但肯定有一个更快更干净的方法。首先为布尔逻辑添加一列,然后执行
groupby
压缩表,然后使用Key
和Result
列遍历并填充True
、False
和Other
列。最后,我删除不需要的列并聚合行相关问题 更多 >
编程相关推荐