【问题标题】:For each loop how to export data to new line in CSV file?对于每个循环,如何将数据导出到 CSV 文件中的新行?
【发布时间】:2020-07-22 22:49:51
【问题描述】:

我正在从多个 URL 中抓取数据,并且收到的数据被拆分为单词。在 for 循环的帮助下,我试图将数据附加到空列表并创建数据框,然后导出到 csv 文件。问题是当导出到 csv 时,它会覆盖上一列,我只能看到一列。如何从每次迭代中将数据导出到每一行。

import urllib.request
from inscriptis import get_text
import pandas as pd
from googletrans import Translator
from time import sleep

url_list = pd.read_csv("/home/user/Downloads/warrior_categories.alcohol.csv")
urls = url_list['domain']


def dataextraction():
    df = pd.DataFrame()
    for url in urls:
        final_url = 'http://' + url
        try:
            html = urllib.request.urlopen(final_url).read().decode('utf-8')
            text = get_text(html)
            extracted_data = text.split()
            refined_data = []
            SYMBOLS = '{}()[].,:;+-*/&|<>=~0123456789'
            for i in extracted_data:
                if i not in SYMBOLS:
                    refined_data.append(i)
            print("\n", "$" * 50, "HEYAAA we got arround: ", len(refined_data), " of keywords! Here are they: ",
                  "$" * 50, "\n")
            print(type(refined_data))
            empty=[]
            for data in refined_data:
                empty.append(data)
            df.append(empty)
        except:
            pass

    df.to_csv('alcohol.csv', index=False)

print(dataextraction())

【问题讨论】:

  • 您应该在 for 循环外定义 DataFrame 并在 for 循环中的 df 中继续附加 empty 并将 csv 导出到 for 循环外

标签: python-3.x pandas for-loop


【解决方案1】:

如果您只需要从循环中添加记录

# need to describe the columns. Just empty df with columns
df = pd.DataFrame([], columns=['name'])
# let's imaging here is your loop with one record
for i in range(5):
    # you conditions here... if blablabla.... and append if you need
    df = df.append({'name': str(i) + 'name'}, ignore_index=True)
print(df)

如果需要从循环中添加df

df = pd.DataFrame([], columns=['name'])
for i in range(5):
    # here is a new df
    tmp_df = pd.DataFrame.from_dict({'name': ('{i}_{k}_name'.format(i=i, k=k) for k in range(i))})
    # you conditions here... if blablabla.... and concat if you need
    df = pd.concat([df, tmp_df], ignore_index=True)
print(df)

希望对你有帮助

【讨论】:

    【解决方案2】:

    您的问题需要更多解释,但我的理解是您想在 csv 中显示所有内置 for 循环的列,可以这样做

    import pandas as pd
    
    
    def dataextraction():
        df = pd.DataFrame()
        for url in urls:
            final_url = 'http://' + url
            try:
                html = urllib.request.urlopen(final_url).read().decode('utf-8')
                text = get_text(html)
                extracted_data = text.split()
                refined_data = []
                SYMBOLS = '{}()[].,:;+-*/&|<>=~0123456789'
                for i in extracted_data:
                    if i not in SYMBOLS:
                        refined_data.append(i)
                print("\n", "$" * 50, "HEYAAA we got arround: ", len(refined_data), " of keywords! Here are they: ",
                      "$" * 50, "\n")
                print(type(refined_data))
                empty=[]
                for data in refined_data:
                    empty.append(data)
                df.append(empty)
            except:
                pass
    
        df.to_csv('alcohol.csv', index=False)
    

    【讨论】:

    • 它没有创建任何 csv 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2021-12-15
    • 1970-01-01
    • 2020-08-22
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多