Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python从文本文件填充熊猫中的数据帧_Python_Pandas - Fatal编程技术网

Python从文本文件填充熊猫中的数据帧

Python从文本文件填充熊猫中的数据帧,python,pandas,Python,Pandas,我有一个熊猫数据框,我们称之为df。它有以下列: ID-这是一个列ID号 文件-包含文件名列表 例如: ID Files 1 [12, 15, 19] 2 [15, 18, 103] 等等。列表中的每个元素对应一个同名的文本文件,因此“12”对应“12.txt” 我想做的是创建一个名为“Content”的第三列,它获取列表中每个文件中的文本,将它们连接在一起并放入该列中。我在试验for循环,但想知道是否有更有效的方法来实现它 谢谢。在纯python中使

我有一个熊猫数据框,我们称之为df。它有以下列:

  • ID-这是一个列ID号
  • 文件-包含文件名列表
  • 例如:

    ID         Files
    1       [12, 15, 19] 
    2       [15, 18, 103]
    
    等等。列表中的每个元素对应一个同名的文本文件,因此“12”对应“12.txt”

    我想做的是创建一个名为“Content”的第三列,它获取列表中每个文件中的文本,将它们连接在一起并放入该列中。我在试验for循环,但想知道是否有更有效的方法来实现它

    谢谢。

    在纯python中使用自定义函数并读取文件(像熊猫一样更快):

    在纯python中使用自定义函数并读取文件(速度更快,如熊猫):

    import ast
    
    def f(x):
        out = []
        path = 'files/'
        #if necessary convert string repr of lists to lists
        x = ast.literal_eval(x)
        for file in x:
            with open('{}{}.txt'.format(path, file)) as f:
                c = ' '.join(f.readlines())
                out.append(c)
        return ' '.join(out)
    
    
    df['content'] = df['Files'].apply(f)
    print (df)
       ID          Files              content
    0   1   [12, 15, 19]        I like pandas
    1   2  [15, 18, 103]  like something else