![](/img/trans.png)
[英]How to obtain the percent change from the first and last value of a DataFrame in Pandas
[英]How to stay with a percent of data from a pandas DataFrame?
假设我有一个这样的pandas DataFrame:
CustomerId Product
1 Apple
2 Orange
3 Apple
4 Watermelon
... ...
1000 Apple
假设我在“产品”栏中有500个苹果。 我想使用一个DataFrame,该DataFrame包含500个苹果中的10%(以及其他类别的100%,也就是说,我希望有一个550行的DataFrame)。 有没有办法有效地做到这一点? 可以随机选择剩下的10%的苹果吗?
您可以为此使用df.sample ,它返回一个随机的项目样本:
condition = df['Product'] != 'Apple'
df_all = df[condition] #This data frame has 100% of all products
df_apple = df[~condition]
percent = int(o.1*df_apple.shape[0]) # calculate 10% of Apple products
df_all = df_all.append(df_all.sample(percent)) #Append random items of apple to df_all
当然,数据帧的数量可以减少,更多的变量用于更好地理解。
查找苹果行:
apples = df["Product"] == 'Apple'
随机选择要保留的行:
HOW_MANY = 0.1 # 10%
keep = np.random.binomial(1, HOW_MANY, size=apples.sum()).astype(bool)
合并非苹果行和苹果行以保持:
results = pd.concat([df[~apples], df[apples][keep]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.