May*_*wal 5 python dictionary dataframe python-3.x pandas
下面是df:
In [1114]: df
Out[1114]:
site_id a b c d e
0 1 4 2 5 50 150
1 2 56 3 6 60 160
2 3 7 4 7 70 170
3 4 8 5 8 80 180
Run Code Online (Sandbox Code Playgroud)
我想创建一个dict列site_id作为键,其他列的列表作为值。
我的尝试:
In [1101]: y = df.site_id.values
In [1109]: x = df[df.columns.difference(['site_id'])].values
In [1112]: d = {i:x[c] for c,i in enumerate(y)}
In [1113]: d
Out[1113]:
{1: array([ 4, 2, 5, 50, 150]),
2: array([ 56, 3, 6, 60, 160]),
3: array([ 7, 4, 7, 70, 170]),
4: array([ 8, 5, 8, 80, 180])}
Run Code Online (Sandbox Code Playgroud)
我能够解决它,但正在寻找更多的pandaic方法。
预期输出:
{1: [4, 2, 5, 50, 150],
2: [56, 3, 6, 60, 160],
3: [7, 4, 7, 70, 170],
4: [8, 5, 8, 80, 180]}
Run Code Online (Sandbox Code Playgroud)
apply agg to df 应该将所有列值发送到列表。将 site_id 设置为索引,然后可以将结果转换为键:值对
df.set_index('site_id').agg(list,1).to_dict()
{1: [4, 2, 5, 50, 150],
2: [56, 3, 6, 60, 160],
3: [7, 4, 7, 70, 170],
4: [8, 5, 8, 80, 180]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1863 次 |
| 最近记录: |