【发布时间】:2019-02-21 16:11:45
【问题描述】:
这类似于Attach a calculated column to an existing dataframe,但是,在 pandas v0.14 中按多列分组时,该解决方案不起作用。
例如:
$ df = pd.DataFrame([
[1, 1, 1],
[1, 2, 1],
[1, 2, 2],
[1, 3, 1],
[2, 1, 1]],
columns=['id', 'country', 'source'])
以下计算有效:
$ df.groupby(['id','country'])['source'].apply(lambda x: x.unique().tolist())
0 [1]
1 [1, 2]
2 [1, 2]
3 [1]
4 [1]
Name: source, dtype: object
但是将输出分配给新列会导致错误:
df['source_list'] = df.groupby(['id','country'])['source'].apply(
lambda x: x.unique().tolist())
TypeError: 插入列的索引与框架索引不兼容
【问题讨论】:
标签: pandas pandas-groupby