python - 如何提取具有条件的某些行?
问题描述
我正在处理一个数据集,该数据集在其第一列中包含情感或类别标签。但是,由于数据集不平衡,我需要为每个类别提取相同数量的行。也就是说,如果有 10 个类别,我只需要从每个类别中选择 100 行样本。结果将是 1000 行样本。
我尝试了什么:
def append_new_rows(df, new_df, s):
c = 0
for index, row in df.iterrows():
if s == row[0]:
if c <= 100:
new_df.append(row)
c += 1
return df_2
for s in sorted(list(set(df.category))):
new_df = append_new_rows(df, new_df, s)
数据集
----------------------------
| category | A | B | C | D |
----------------------------
| happy | ...| ...|...|...|
| ... | ...| ...|...|...|
| sadness | ...| ...|...|...|
预期产出
----------------------------
| category | A | B | C | D |
----------------------------
| happy | ...| ...|...|...|
... 100 samples of happy
| ... | ...| ...|...|...|
| sadness | ...| ...|...|...|
... 100 samples of sadness
...
...
1000 sampple rows
解决方案
def append_new_df(df, df_2, s, n):
c = 1
for index, row in df.iterrows():
if s == row[0]:
if c <= n:
df_2 = df_2.append(row)
c += 1
return df_2
你就在那里,你只需要做这样的事情
推荐阅读
- php - PHP访问方括号中的嵌套json元素
- javascript - 对象作为 React 子级无效(找到:带键的对象)。如果您打算渲染一组孩子,请改用数组
- r - 如何在一张图中绘制 2 个直方图(不同的行长)(ggplot)
- csvhelper - 如何将特定时区的日期时间解析为 UTC?
- gnuplot - 在gnuplot中用`front`键交换对象的层
- javascript - 加载资源失败:net::ERR_CACHE_OPERATION_NOT_SUPPORTED
- osgi - 使用 STATIC 策略绑定 OSGi 声明式服务的顺序
- python - Apache 无法找到烧瓶应用程序路径
- wordpress - 如何使用 docker-compose 的官方 wordpress 图像修复 wp-content 的文件权限
- node.js - 如何从 package-lock.json 文件制作 package.json