我正在处理一个问题,这个问题要求我使用split-apply-combine执行几个操作。除了最后一个问题,我得到了大多数问题的答案。
这是最后一个问题:
如果某一类别的最高价格超过3.00美元,则将该类别中的所有价格降低10%。返回新价格列的系列。
import pandas as pd
import numpy as np
grocery = pd.DataFrame({'category':['produce', 'produce', 'meat',
'meat', 'meat', 'cheese', 'cheese'],
'item':['celery', 'apple', 'ham', 'turkey', 'lamb',
'cheddar', 'brie'],
'price':[.99, .49, 1.89, 4.34, 9.50, 6.25, 8.0]})
grouped = grocery.groupby('category')
answer = grouped.transform(lambda x: 0.9 * x if np.max(x) > 3 else x)我想我得到了这一类别中所有价格降低10%的部分。然而,我遇到了一个问题,我如何才能将我的“答案”作为一系列新的价格列返回。
当我将我所拥有的(‘答案’)提交到提交页面时,价格的值是正确的,但它不被视为一个系列。我知道pd.Series,但不确定如何在这里将其转换为系列。
有人能给我一个见解吗?
发布于 2019-01-06 16:20:59
只需分配给新列,因为GroupBy.transform返回的系列与原始DataFrame具有相同的大小,而且对于一般解决方案,有必要在groupby之后指定列price仅处理此列:
grouped = grocery.groupby('category')['price']
print (type(grouped.transform(lambda x: 0.9 * x if np.max(x) > 3 else x)))
<class 'pandas.core.series.Series'>
print (grouped.transform(lambda x: 0.9 * x if np.max(x) > 3 else x))
0 0.990
1 0.490
2 1.701
3 3.906
4 8.550
5 5.625
6 7.200
Name: price, dtype: float64如果需要赋值到列price
grocery['price'] = grouped.transform(lambda x: 0.9 * x if np.max(x) > 3 else x)
print (grocery)
category item price
0 produce celery 0.990
1 produce apple 0.490
2 meat ham 1.701
3 meat turkey 3.906
4 meat lamb 8.550
5 cheese cheddar 5.625
6 cheese brie 7.200和使用assign的解决方案
grocery = (grocery.assign(price = lambda x: x.groupby('category')['price']
.transform(lambda x: 0.9 * x
if np.max(x) > 3
else x)))https://stackoverflow.com/questions/54059788
复制相似问题