从Python目录中的多个CSV文件中提取特定列

意志9

我的目录中大约有200个CSV文件,其中包含不同的列,但有些文件中有我要提取的数据。我要拉的一列称为“ Programme”(行的顺序不同,但名称相同),另一列包含“ would荐”(并非所有措辞都相同,但它们都将包含该措辞)。最终,我想为每个CSV提取这些列下的所有行,并将它们附加到仅包含这两列的数据框中。我尝试过仅使用一个CSV来完成此操作,但无法使其正常工作。这是我尝试过的:

import pandas as pd
from io import StringIO

df =  pd.read_csv("test.csv")

dfout = pd.DataFrame(columns=['Programme', 'Recommends'])

for file in [df]:
    dfn = pd.read_csv(file)
    matching = [s for s in dfn.columns if "would recommend" in s]
    if matching:
        dfn = dfn.rename(columns={matching[0]:'Recommends'})
        dfout = pd.concat([dfout, dfn], join="inner")

print(dfout)

我收到以下错误消息,因此我认为这是一个格式问题(它不喜欢熊猫df?):ValueError(msg.format(_type = type(filepath_or_buffer)))ValueError:无效的文件路径或缓冲区对象类型: <class'pandas.core.frame.DataFrame'>

当我尝试这个:

csv1 = StringIO("""Programme,"Overall, I am satisfied with the quality of the programme",I would recommend the company to a friend or colleague,Please comment on any positive aspects of your experience of this programme
Nursing,4,4,IMAGE
Nursing,1,3,very good
Nursing,4,5,I enjoyed studying tis programme""")

csv2 = StringIO("""Programme,I would recommend the company to a friend,The programme was well organised and running smoothly,It is clear how students' feedback on the programme has been acted on
IT,4,2,4
IT,5,5,5
IT,5,4,5""")

dfout = pd.DataFrame(columns=['Programme', 'Recommends'])

for file in [csv1,csv2]:
    dfn = pd.read_csv(file)
    matching = [s for s in dfn.columns if "would recommend" in s]
    if matching:
        dfn = dfn.rename(columns={matching[0]:'Recommends'})
        dfout = pd.concat([dfout, dfn], join="inner")

print(dfout)

这工作正常,但我需要读入CSV文件。有任何想法吗?

以上示例的预期输出: 在此处输入图片说明

意志9

下面的作品:

import pandas as pd
import glob

dfOut = []

for myfile in glob.glob("*.csv"):
    tmp = pd.read_csv(myfile, encoding='latin-1')
    
    matching = [s for s in tmp.columns if "would recommend" in s]
    if len(matching) > 0:
        tmp.rename(columns={matching[0]: 'Recommend'}, inplace=True)
        tmp = tmp[['Subunit', 'Recommend']]
        dfOut.append(tmp)
        
df = pd.concat(dfOut)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从文件中提取特定列?

提取csv文件特定的列以在Python中列出

PowerShell从csv中提取特定列并存储在变量中

如何从python中的文件中提取特定信息

如何从Python中以空格分隔的.DAT文件中提取多个列

想要从耳朵文件中提取特定的jar文件并将其存储在特定目录中

在目录中提取特定文件-Windows

R:如何在多个csv中提取列,然后在一个文件夹中写入多个csv

从多个CSV文件中提取几种模式

从多个json文件中提取特定文本

使用Python从CSV文件中提取列数据

从多个TXT文件中提取数据并在Python中创建摘要CSV文件

从多个CSV文件中提取信息,并在第三列中写入新的CSV文件

如何使用Powershell从多个csv文件中提取一个特定的列(没有标题,说第2列)?

如何从Python中的CSV文件中提取JSON对象?

如何从多个其他文件的特定列中的一个文件中提取所有行?

在 Python 中从文件中提取特定数据

从python中的JSON文件中提取多个对象

如何从目录中的文件中提取特定信息?

从 csv 文件中提取特定列,并使用 Python 在 Lambda 中转换为字符串

从 csv 文件中的字符串中提取特定信息

从多个文件中提取特定行

Python - 爬取目录、从 ZIP 中提取 CSV 文件以及组合多个 CSV

使用 Python 从文本(在 CSV 文件中)中提取数据

如何从python中的.tar存档中提取特定文件?

从 Python 中的多个 Excel 文件中提取必要的列

从子目录python中提取csv文件

如何在python中提取csv中的列

如何从目录的多个 csv 中提取特定值,并将它们附加到数据框中?