我正在对我的数据进行一些数据增强。
基本上它们看起来像这样:
country. size. price. product
CA. 1. 3.99. 12
US. 1. 2.99. 12
BR. 1. 10.99. 13
Run Code Online (Sandbox Code Playgroud)
我想要做的是,因为尺寸固定为 1,所以我想为每个国家/地区、每个产品添加 3 个尺寸,并相应提高价格。因此,如果尺寸为 2,则价格为 1 乘以 2 的价格,依此类推...
所以基本上,我正在寻找这个:
country. size. price. product
CA. 1. 3.99. 12
CA. 2. 7.98. 12
CA. 3. 11.97. 12
CA. 4. 15.96. 12
US. 1. 2.99. 12
US. 2. 5.98. 12
US. 3. 8.97. 12
US. 4. 11.96. 12
BR. 1. 10.99. 13
BR. 2. 21.98. 13
BR. 3. 32.97. 13
BR. 4. 43.96. 13
Run Code Online (Sandbox Code Playgroud)
对熊猫执行此操作的好方法是什么?我尝试循环执行此操作,iterrows()但这对于我的数据来说并不是一个快速的解决方案。那么我错过了什么吗?
用于Index.repeat添加新行,然后聚合GroupBy.cumsum并添加计数器GroupBy.cumcount,最后重置索引为默认唯一索引:
df = df.loc[df.index.repeat(4)]
df['size'] = df.groupby(level=0).cumcount().add(1)
df['price'] = df.groupby(level=0)['price'].cumsum()
df = df.reset_index(drop=True)
print (df)
country size price product
0 CA 1 3.99 12
1 CA 2 7.98 12
2 CA 3 11.97 12
3 CA 4 15.96 12
4 US 1 2.99 12
5 US 2 5.98 12
6 US 3 8.97 12
7 US 4 11.96 12
8 BR 1 10.99 13
9 BR 2 21.98 13
10 BR 3 32.97 13
11 BR 4 43.96 13
Run Code Online (Sandbox Code Playgroud)
另一个想法没有cumcount,但有numpy.tile:
add = 3
df1 = df.loc[df.index.repeat(add + 1)]
df1['size'] = np.tile(range(1, add + 2), len(df))
df1['price'] = df1.groupby(level=0)['price'].cumsum()
df1 = df1.reset_index(drop=True)
print (df1)
country size price product
0 CA 1 3.99 12
1 CA 2 7.98 12
2 CA 3 11.97 12
3 CA 4 15.96 12
4 US 1 2.99 12
5 US 2 5.98 12
6 US 3 8.97 12
7 US 4 11.96 12
8 BR 1 10.99 13
9 BR 2 21.98 13
10 BR 3 32.97 13
11 BR 4 43.96 13
Run Code Online (Sandbox Code Playgroud)