我應該按年份和 id 聚合一個銷售表,然后在表中添加一個年齡列。不幸的是,當我添加最后一列時,我只得到該列的 NaN 值。像這樣:
|year|id|sales|age|
__________________
2022 |1 | 200| NaN|
|2 | 342| NaN|
2021 |34| 500| NaN|
|10| 20 | NaN|
|7 | 4200| Nan|
我的 df 中有一個“年齡”列,所以每個 id 都有一個分配給它的年齡。這是我的代碼:
df['sales'] = df.price*df.quantity
df['year'] = pd.DatetimeIndex(df['date']).year
def table(df):
test = order.groupby(['year','id'])\
.agg(sales = ('sales', 'sum'))\
.assign(age = df['age'])
return table
table(df)
有人可以告訴我為什么它沒有按照預期的方式顯示年齡嗎?
uj5u.com熱心網友回復:
它給出了NaN值,因為它不明白你想要什么。year當您按和分組時,您正在將一列分配給較小的資料框id。所以問題是,您希望該列發生age什么?
使用我的虛擬資料集:
df = pd.DataFrame({'year': [2021, 2021, 2021, 2022],
'id': [1, 1, 2, 1],
'sales': [20, 30, 40, 50],
'age': [3, 4, 5, 6]})
平均年齡
如果您想求和或取列年齡的平均值,請執行與以下類似的操作sales:
df.groupby(['year', 'id']).agg(sales = ('sales', 'sum'), age = ('age', 'mean'))
輸出:
sales age
year id
2021 1 50 3.5
2 40 5.0
2022 1 50 6.0
給出年齡的所有唯一值
您想獲取所有年齡值的串列,請使用引數unique而不是mean:
df.groupby(['year', 'id']).agg(sales = ('sales', 'sum'), age = ('age', 'unique'))
輸出:
sales age
year id
2021 1 50 [3, 4]
2 40 [5]
2022 1 50 [6]
年齡的單一值
如果年份/id 組內的年齡相同,則可以取最小值(或最大值,因為它們相同,所以沒關系)。請注意,在我的虛擬資料集中,它們不一樣:
df.groupby(['year', 'id']).agg(sales = ('sales', 'sum'), age = ('age', 'min'))
輸出:
sales age
year id
2021 1 50 3
2 40 5
2022 1 50 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516127.html
