在Python中使用pandas在多个CSV文件中搜索字符串。

huangapple go评论60阅读模式
英文:

search for a string in multiple csv files in python using pandas

问题

我正在尝试在多个CSV文件中搜索一个字符串/值,并将其保存在一个新的CSV文件中。我的代码没有出现任何错误,但返回一个空的CSV文件。

以下是我的代码:

import pandas as pd
import glob

path = '多个csv文件的路径'

files = glob.glob(path + '/*.csv')
for filename in files:
    df = pd.read_csv(filename, sep=',')
    x = df[df.apply(lambda col: col.astype(str).str.contains('要搜索的值').any(), axis=1)]

x.to_csv('result.csv', index=False)

如果你的结果CSV文件为空,可能需要检查以下几点:

  1. 确保path变量包含正确的文件路径。
  2. 确保CSV文件中包含要搜索的值,否则将返回空文件。
  3. 检查CSV文件的分隔符是否正确。你的代码中使用的是逗号分隔符(,),确保它与你的CSV文件的实际格式匹配。
  4. 确保CSV文件的编码和格式没有问题,否则可能会影响读取和写入操作。

如果上述检查都正确,但问题仍然存在,那么可能需要进一步调试代码以查找错误。

英文:

I am trying to search a string/value in multiple csv files and save that in a new csv file. My code doesn't give me any error but returns an empty csv file

Here's my code:

import pandas as pd
import glob
path='path/to/multiple/csv/files'

files=glob.glob(path + '/*.csv')
for filename in files:
    df=pd.read_csv(filename,sep=',')
    x=df[df.apply(lambda col: col.astype(str).str.contains('myvalue').any(),axis=1)]

x.to_csv('result.csv',index=False)

答案1

得分: 1

创建空列表,通过DataFrames填充它,最后使用concat将它们合并为最终的DataFrame:

import glob
import pandas as pd

# 获取匹配指定路径下的所有.csv文件
files = glob.glob(path + '/*.csv')

out = []

# 遍历每个文件
for filename in files:
    # 读取CSV文件
    df = pd.read_csv(filename, sep=',')
    
    # 选择包含'myvalue'的行
    x = df[df.apply(lambda col: col.astype(str).str.contains('myvalue').any(), axis=1)]
    
    # 将选择的部分添加到列表
    out.append(x)

# 使用concat合并所有DataFrames,并保存为'result.csv'
pd.concat(out).to_csv('result.csv', index=False)
英文:

Create empty list, fill it by DataFrames and for final DataFrame join together by concat:

files=glob.glob(path + '/*.csv')

out = []
for filename in files:
    df=pd.read_csv(filename,sep=',')
    x=df[df.apply(lambda col: col.astype(str).str.contains('myvalue').any(),axis=1)]
    out.append(x)

pd.concat(out).to_csv('result.csv',index=False)

huangapple
  • 本文由 发表于 2023年7月10日 13:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定