繁体   English   中英

尝试在循环内附加两个Pandas DataFrame,导致第一个被覆盖

[英]Attempting to append two Pandas DataFrames within a loop causes the first to be overwritten

我有这个功能(除其他外)应该读取棒球比赛的csv文件,以创建所有球队的列表(此部分有效)。 该文件包含客场比赛数据和主场比赛数据,其想法是拆分数据以更改列并最后附加比赛数据,而不管位置如何(这最后一部分不起作用)。 代码没有将我的客场和主场比赛附加到一个数据框中,而是完全覆盖了主场比赛。

我已经附上我的代码以及问题。

非常感谢您的帮助。

df = pd.read_csv('C:\\Users\\data.csv', index_col=0)

unique = df['Team Home'].unique()
inplace = ['H', 'A']
myway = pd.DataFrame()
for i in range(len(unique)):
    for inp in inplace:
        if inp == 'H':    #loop to find column names with 'Home' and 'Away' Labels
            located = 'Home'
            character = 'H'
        else:
            located = 'Away'
            character = 'A'
        noseclean_h = df[df['Team {}'.format(located)].isin([unique[i]])]
        noseclean_h = noseclean_h.sort_values('Date')
        home = [rr for rr in rolling_haiting if character in rr]
        new_home = [rr.replace('{}'.format(located), '').strip() if character in rr and len(rr) > 2
                    else rr.replace(character, '') for rr in home]
        new_home.append('Date')
        new_home.append('Team')
        home.append('Date')
        home.append('Team {}'.format(located))
        ncleaned = ncleaned[home]
        d = dict(zip(home, new_home))
        ncleaned .rename(columns=d, inplace=True)
        nosecleaned_h['Date'] = pd.to_datetime(ncleaned ['Date'])
        nosecleaned_h.set_index('Date', inplace=True) # set index to date to prevent overlapping
        nosecleaned_h = nosecleaned_h.append(nosecleaned_h, ignore_index=False)
    print(nosecleaned_h)
....etc

在每个循环中,您都在重新分配变量noseclean_h

noseclean_h = df[df['Team {}'.format(located)].isin([unique[i]])]

然后,在每个循环上, nosecleaned_h = nosecleaned_h.append(nosecleaned_h, ignore_index=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM