【问题标题】:Append to Pandas dataframe while looping over lines?在遍历行时附加到 Pandas 数据框?
【发布时间】:2017-10-23 08:31:57
【问题描述】:

我还是 Pandas 的新手。是否可以在循环线路时启动并附加到 Pandas 数据帧?我的尝试如下,但它创建了一个包含 1 列而不是 6 列的数据框。将修改后的输入保存到 csv 文件然后用 Pandas 读取该 csv 文件会更容易吗?我现在可能会这样做。谢谢!

import requests
import pandas as pd

url = 'https://raw.githubusercontent.com/23andMe/yhaplo/master/input/isogg.2016.01.04.txt'
r = requests.get(url)
for i, line in enumerate(r.text.splitlines()):
    l = line.strip().split('\t')
    ## The header is on the first line.
    if i == 0:
        df = pd.DataFrame([s.strip() for s in l])
    ## Lines with 6 columns.
    elif len(l) == 6:
        df = df.append(pd.DataFrame([s.strip() for s in l]))
    ## Lines with 7 columns.
    elif len(l) == 7:
        df = df.append(pd.DataFrame([l[i].strip() for i in (0, 2, 3, 4, 5, 6)]))

【问题讨论】:

    标签: python python-3.x pandas dataframe append


    【解决方案1】:

    您可以将整个文件作为 csv 流加载到 Dataframe,而无需遍历每一行。

    import requests
    import pandas as pd
    import csv
    
    url = 'https://raw.githubusercontent.com/23andMe/yhaplo/master/input/isogg.2016.01.04.txt'
    r = requests.get(url)
    df = pd.DataFrame(list(csv.reader(r.text.splitlines(), delimiter='\t')))
    

    更新:

    现在应该可以了。

    for i, line in enumerate(r.text.splitlines()):
        l = line.strip().split('\t')
        ## The header is on the first line.
        if i == 0:
            df = pd.DataFrame(columns = [s.strip() for s in l])
        ## Lines with 6 columns.
        elif len(l) == 6:
            df = df.append(pd.DataFrame(columns=df.columns,data=[[s.strip() for s in l]]))
        ## Lines with 7 columns.
        elif len(l) == 7:
            df = df.append(pd.DataFrame(columns=df.columns, data=[[l[i].strip() for i in (0, 2, 3, 4, 5, 6)]]))
    

    【讨论】:

    • 谢谢,但不幸的是这不起作用,因为大多数行有 6 列,而其他行有 7 列。这就是为什么我必须修改它们。
    • 哦,对了,我已经更新了你的代码,现在应该可以工作了。(可能有点慢)
    • 非常感谢!它确实很慢,但它确实有效。这行对我很有帮助:df = pd.DataFrame(columns = [s.strip() for s in l])
    • 不客气。如果有帮助,请采纳答案。
    【解决方案2】:

    受到this answer的启发,我选择了这个解决方案:

    import requests
    import pandas as pd
    
    url = 'https://raw.githubusercontent.com/23andMe/yhaplo/master/input/isogg.2016.01.04.txt'
    r = requests.get(url)
    table = []
    for i, line in enumerate(r.text.splitlines()):
        l = line.strip().split('\t')
        ## The first line is the header.
        if i == 0:
            table.append([s.strip() for s in l])
        ## Rows with 6 colums.
        elif len(l) == 6:
            table.append([s.strip() for s in l])
        ## Rows with 7 columns.
        elif len(l) == 7:
            table.append([l[i].strip() for i in (0, 2, 3, 4, 5, 6)])
        ## Skip rows with neither 6 nor 7 columns.
        else:
            pass
    df = pd.DataFrame(table)
    

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多