【问题标题】:Appending data to Pandas DataFrame with for loop使用 for 循环将数据附加到 Pandas DataFrame
【发布时间】:2019-04-13 03:59:07
【问题描述】:

我有一个包含四个 URL 的列表,我正在尝试循环并作为 DataFrame 读入 Pandas。问题是它只会读取其中一个 .csv 文件。

以下是我的代码:

#Import necessary libraries
import pandas as pd
import time

#URL's for weekly projections on rotogrinders.com

url =['https://rotogrinders.com/projected-stats/nfl-qb.csv?site=draftkings',\
      'https://rotogrinders.com/projected-stats/nfl-rb.csv?site=draftkings',\
      'https://rotogrinders.com/projected-stats/nfl-wr.csv?site=draftkings',\
      'https://rotogrinders.com/projected-stats/nfl-te.csv?site=draftkings']

#Loop through each url, read the .csv into a DataFrame,append all together, 
#then write the DataFrame to a .csv file

file_name = 'weekly_projections_'
timestr = time.strftime('%Y%m%d')

df = pd.DataFrame()

for data in url:
    df = pd.read_csv(data)
    df.append
    df.to_csv(file_name + timestr + '.csv')

当我通过 . info() 你可以看到我只得到了 1/4 的结果。我希望有 200 多个条目

df.info

    <class 'pandas.core.frame.DataFrame'>
RangeIndex: 28 entries, 0 to 27
Data columns (total 8 columns):
Baker Mayfield    28 non-null object
5400              28 non-null int64
CLE               28 non-null object
QB                28 non-null object
ATL               28 non-null object
30.18435          28 non-null float64
9.81225           28 non-null float64
18.69             28 non-null float64
dtypes: float64(3), int64(1), object(4)
memory usage: 1.8+ KB

有人有什么建议吗?

【问题讨论】:

    标签: python-3.x pandas spyder


    【解决方案1】:

    你可以用你的for循环做这样的事情:

    在开头声明一个空数据框:

    tmp = pd.DataFrame()
    for data in url:
        df = pd.read_csv(data)
        tmp = tmp.append(df)
        #df.to_csv(file_name + timestr + '.csv')
    
    # Now, `tmp` will have dataframes for all URL's. You can then write this to `csv
    
    tmp.to_csv(file_name + timestr + '.csv')
    

    如果这是你想要的,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2021-03-15
      • 2016-10-13
      • 2019-07-12
      • 2019-05-31
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多