我有这样一个数据帧:在数据帧拼合多列一列
id other_id_1 other_id_2 other_id_3
1 100 101 102
2 200 201 202
3 300 301 302
我想这一点:
id other_id
1 100
1 101
1 102
2 200
2 201
2 202
3 300
3 301
3 302
我可以很容易地得到我想要的输出是这样的:
to_keep = {}
for idx in df.index:
identifier = df.loc[idx]['id']
to_keep[identifier] = []
for col in ['other_id_1', 'other_id_2', 'other_id_3']:
row_val = df.loc[idx][col]
to_keep[identifier].append(row_val)
这给我这个:
{1: [100, 101, 102], 2: [200, 201, 202], 3: [300, 301, 302]}
我可以很容易地写到一个文件。不过,我正在努力在本土熊猫中做到这一点。我猜想这似乎换位会比较简单,但我在努力...
我看你使用你的最爱。 ;-) –
@cᴏʟᴅsᴘᴇᴇᴅ是的..只是想让更多的人注意到这个功能... – Wen