python - 如何分别提取每列中的重复值?
问题描述
我只想分别提取每列中出现两次或多次的值,并将它们写入带有列标题的单独文件中。
示例文件:(实际 csv 文件为 1.5 Gb,此处包括摘要)第一行是每列的标题行
AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3
我曾尝试用 R 甚至 Python panda 编写代码,但未能得到结果。
预期结果:
AO1 BO1 CO1 DO1 EO1 FO1
pep2 xcv4 iop3 typ3 ert3 rtf5
pep2 xcv4 iop3 typ3 ert3 rtf5
pep2 xcv4 typ3 rtf5
wer3 rtf5
wer3 rtf5
解决方案
import pandas as pd
from StringIO import StringIO
df = pd.read_csv(StringIO("""AO1,BO1,CO1,DO1,EO1,FO1
pep2,red2,ter3,typ3,ghl4,rtf5
ghp2,asd2,ghj3,typ3,ghj3,ert4
typ2,sdf2,rty3,ert4,asd2,sdf2
pep2,xcv2,bnm3,wer3,vbn3,wer2
dfg4,fgh3,uio2,wer3,ghj2,rtf5
dfg6,xcv4,dfg3,ret5,ytu2,rtf5
pep2,xcv4,ert1,dgf2,ert3,fgh3
okj2,xcv4,jkl3,ghr4,cvb3,rtf5
poi2,tyu2,iop3,cvb3,hjk5,rtf5
qwe2,wer2,iop3,typ3,ert3,cvb3"""))
d = {}
for col in df.columns:
repeated_values = df[col].value_counts()[df[col].value_counts() >= 2].index.tolist()
cond = df[col].isin(repeated_values)
d[col] = df[cond][col]
final = pd.concat(d, axis=1)
推荐阅读
- xcode - 如何在 premake5 配置中定义 xcode 的方案和目标
- java - Velocity 2.0 无法在 jar 中找到模板资源
- perl - Perl代码解释
- gcc - CBLAS 安装问题:未定义对 `_gfortran_store_exe_path' 的引用
- json - JSON 响应在 Google DevTools 中显示不安全的内联错误?
- c++ - EVP_DigestVerifyUpdate OpenSSL 的替代方案
- python - VSCode Python 测试发现失败(2018 年 6 月)
- html - HTML 为什么我的边框中的 span 和 div 有区别?
- javascript - 如何将 base64 字符串解码为图像并使用 PHP 将其保存在我的服务器上
- java - 从excel模板读取数据并写入同一个文件