我有一个聊天对话的数据集,如下所示(其中message_id
是数据库中所有消息的索引(
| message_id | to_user | from_user | message |
|------------|---------|-----------|--------------|
| 123 | al | sal | hi |
| 871 | al | hal | hey |
| 989 | al | bob | me too |
| 900 | sal | sal | hello |
| 107 | bob | al | i'm bob |
| 242 | sal | al | how are you? |
| 101 | al | bob | hi, i'm al |
| 898 | sal | al | i'm good |
我想做的是对这张表进行排序,以反映两个人之间的对话。因此,它将首先对来自to_user
和他们聊天的每个from_user
的所有对话进行分组,然后对to_user
和from_user
之间的每个对话按其message_id进行排序,以便反映来回对话。
| message_id | to_user | from_user | message |
|------------|---------|-----------|--------------|
| 101 | al | bob | hi, i'm al |
| 107 | bob | al | i'm bob |
| 989 | al | bob | me too |
| 123 | al | sal | hi |
| 242 | sal | al | how are you? |
| 871 | al | sal | hey |
| 898 | sal | al | i'm good |
| 900 | sal | al | hello |
我将如何在熊猫身上做到这一点?
我们可以使用np.sort
跨行对值进行排序,这样我们就有了指定参与者但不指定方向的列,然后使用DataFrame.sort_values
:按对话和消息id进行排序
df[['person_a', 'person_b']] = np.sort(df[['to_user', 'from_user']])
df = df.sort_values(['message_id', 'person_a', 'person_b'], ignore_index=True)
message_id to_user from_user message person_a person_b
0 101 al bob hi, i'm al al bob
1 107 bob al i'm bob al bob
2 989 al bob me too al bob
3 123 al sal hi al sal
4 242 sal al how are you? al sal
5 871 al sal hey al sal
6 898 sal al i'm good al sal
7 900 sal al hello al sal
我们可以在处理完这些附加列后drop
:
df[['person_a', 'person_b']] = np.sort(df[['to_user', 'from_user']])
df = df.sort_values(
['message_id', 'person_a', 'person_b'], ignore_index=True
).drop(columns=['person_a', 'person_b'])
df
:
message_id to_user from_user message
0 101 al bob hi, i'm al
1 107 bob al i'm bob
2 989 al bob me too
3 123 al sal hi
4 242 sal al how are you?
5 871 al sal hey
6 898 sal al i'm good
7 900 sal al hello
设置和导入(经过编辑以匹配输出(:
import numpy as np
import pandas as pd
df = pd.DataFrame({
'message_id': [123, 871, 989, 900, 107, 242, 101, 898],
'to_user': ['al', 'al', 'al', 'sal', 'bob', 'sal', 'al', 'sal'],
'from_user': ['sal', 'sal', 'bob', 'al', 'al', 'al', 'bob', 'al'],
'message': ['hi', 'hey', 'me too', 'hello', "i'm bob", 'how are you?',
"hi, i'm al", "i'm good"]
})