我试图使用Pandas将两列转换为一个列,该列是两个转换列的字典表示。
df = DataFrame({'Metrics' : [[("P", "P"), ("Q","Q")], ("K", "K"), ("Z", "Z")],
'Stage_Name' : ["P", "K", "Z"],
'Block_Name' : ["A", "B", "A"]})
基本上我想要合并Metrics
和Stage_Name
:
进入另一个名为merged
的列,例如,第一行将是:
{'P': [('P', 'P'), ('Q', 'Q')]}
我知道如何将一行转换为字典表示,但是,我不知道如何在没有for循环的情况下对所有行执行此操作:
something = df.iloc[[0]].set_index('Stage_Name')['Metrics'].to_dict()
print something
Output: {'P': [('P', 'P'), ('Q', 'Q')]}
稍后我想基于Block_Name
进行汇总,因此对于合并列,结果将是为Block_Name
添加的两个词典:A
。
{'P': [('P', 'P'), ('Q', 'Q')], 'Z' : [('Z', 'Z')] }
对于Stage_Name
和Metrics
,我只是将其附加到列表中,如下所示:
grouped = df.groupby(df['Block_Name'])
df_2 = grouped.aggregate(lambda x: tuple(x))
有人能指出我正确的方向吗?谢谢!
答案 0 :(得分:5)
df['Merged'] = [{key: val} for key, val in zip(df.Stage_Name, df.Metrics)]
>>> df
Block_Name Metrics Stage_Name Merged
0 A [(P, P), (Q, Q)] P {u'P': [(u'P', u'P'), (u'Q', u'Q')]}
1 B (K, K) K {u'K': (u'K', u'K')}
2 A (Z, Z) Z {u'Z': (u'Z', u'Z')}
然后您的代码会产生所需的结果:
grouped = df.groupby(df['Block_Name'])
df_2 = grouped.aggregate(lambda x: tuple(x))[['Metrics', 'Stage_Name']]
>>> df_2
Metrics Stage_Name
Block_Name
A ([(P, P), (Q, Q)], (Z, Z)) (P, Z)
B ((K, K),) (K,)
定时:
%timeit df['Merged'] = [{key: val} for key, val in zip(df.Stage_Name, df.Metrics)]
10000 loops, best of 3: 162 µs per loop
%timeit df['merged'] = df.apply(lambda row: {row['Stage_Name']:row['Metrics']}, axis=1)
1000 loops, best of 3: 332 µs per loop
答案 1 :(得分:1)
IIUC正确然后您将apply
与lambda
:
In [19]:
df['merged'] = df.apply(lambda row: {row['Stage_Name']:row['Metrics']}, axis=1)
df
Out[19]:
Block_Name Metrics Stage_Name merged
0 A [(P, P), (Q, Q)] P {'P': [('P', 'P'), ('Q', 'Q')]}
1 B (K, K) K {'K': ('K', 'K')}
2 A (Z, Z) Z {'Z': ('Z', 'Z')}