You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas筛选并复制file列重复指定次数的行?

Pandas筛选并复制指定重复次数的行

没问题,这就帮你搞定这个需求。咱们直接上解决方案,再一步步解释:

完整代码实现

import pandas as pd

# 你的原始数据
df1 = pd.DataFrame({ 
    'file': ['file1','file1','file1','file2','file2','file2','file3','file3','file4'], 
    'prop1': [True,False,True,False,False,False,True,False,False], 
    'prop2': [False,False,False,False,True,False,False,True,False], 
    'prop3': [False,True,False,True,False,True,False,False,True] 
})

# 1. 找出出现次数恰好为3次的file名称
valid_files = df1['file'].value_counts()[df1['file'].value_counts() == 3].index

# 2. 筛选出这些file对应的所有行(如果需要复制行,看下面的扩展)
result = df1[df1['file'].isin(valid_files)]

# 扩展:如果需要把筛选后的行**复制一遍**(比如原6行变12行),取消下面这行注释
# result = pd.concat([result, result], ignore_index=True)

# 查看结果
print(result)

代码解释

  • 步骤1:用value_counts()统计每个file的出现频次,然后筛选出频次等于3的文件名,存到valid_files里——这里得到的就是file1和file2。
  • 步骤2:用isin()方法从原DataFrame中提取所有file属于valid_files的行,这就是你要的基础结果。
  • 扩展说明:如果你的“复制”是指把筛选后的行再重复一份(比如让file1的3行变成6行),就取消pd.concat那行的注释,它会把结果和自身拼接,ignore_index=True用来重置行索引,避免重复。

运行结果

运行上面的基础代码,输出就是你给出的预期结果:

file  prop1  prop2  prop3
0  file1   True  False  False
1  file1  False  False   True
2  file1   True  False  False
3  file2  False  False   True
4  file2  False   True  False
5  file2  False  False   True

内容的提问来源于stack exchange,提问作者Contra111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:49:00