在同一操作中聚合并加入同一 table - python
aggregate and join on the same table in the same operation - python
在 R 中,您可以轻松地在一行中聚合和加入相同的 data.table。我想知道 Python 中是否有我可以使用的等价物,而不必在 table 上单独聚合然后合并它。
这是 R 的等价物:
> require(data.table)
> DT = data.table(Col1 = c('A','A','A','B','B','B'), Col2 = c(1,2,3,4,5,6))
> DT[, Col2_mean := mean(Col2), by=.(Col1)] # this is the line I'm hoping to produce in Python, in one line!
> DT
Col1 Col2 Col2_mean
1: A 1 2
2: A 2 2
3: A 3 2
4: B 4 5
5: B 5 5
6: B 6 5
此外,是否可以执行多个聚合操作(例如 max())并同时合并?
对于 Python,这是开始的数据框:
import pandas as pd
DF = pd.DataFrame(data={'Col1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Col2': [1,2,3,4,5,6]})
你可以用 pandas 和 groupby
和 transform
:
>>> df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Col2': [1, 2, 3, 4, 5, 6]})
>>> df['Col2_mean'] = df.groupby('Col1')['Col2'].transform('mean')
>>> df
Col1 Col2 Col2_mean
0 A 1 2
1 A 2 2
2 A 3 2
3 B 4 5
4 B 5 5
5 B 6 5
>>>
在 R 中,您可以轻松地在一行中聚合和加入相同的 data.table。我想知道 Python 中是否有我可以使用的等价物,而不必在 table 上单独聚合然后合并它。
这是 R 的等价物:
> require(data.table)
> DT = data.table(Col1 = c('A','A','A','B','B','B'), Col2 = c(1,2,3,4,5,6))
> DT[, Col2_mean := mean(Col2), by=.(Col1)] # this is the line I'm hoping to produce in Python, in one line!
> DT
Col1 Col2 Col2_mean
1: A 1 2
2: A 2 2
3: A 3 2
4: B 4 5
5: B 5 5
6: B 6 5
此外,是否可以执行多个聚合操作(例如 max())并同时合并?
对于 Python,这是开始的数据框:
import pandas as pd
DF = pd.DataFrame(data={'Col1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Col2': [1,2,3,4,5,6]})
你可以用 pandas 和 groupby
和 transform
:
>>> df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'B'], 'Col2': [1, 2, 3, 4, 5, 6]})
>>> df['Col2_mean'] = df.groupby('Col1')['Col2'].transform('mean')
>>> df
Col1 Col2 Col2_mean
0 A 1 2
1 A 2 2
2 A 3 2
3 B 4 5
4 B 5 5
5 B 6 5
>>>