首页 > 解决方案 > 同时写入数据框中的多个列

问题描述

我有这段代码,我正在写入数据框中的多个列。有没有办法简化它,使它发生在一行代码而不是多行代码中?

tempSummary.at[name,'Wins'] = wins
tempSummary.at[name,'Singles'] = singles
tempSummary.at[name,'Doubles'] = dubs
tempSummary.at[name,'Triples'] = trips
tempSummary.at[name,'Quads'] = quads        
tempSummary.at[name,'Raw Score'] = rawScore
tempSummary.at[name,'Total Score'] = tempTotal

标签: python-3.xpandasdataframe

解决方案


使用.loc而不是.atwhich 允许列表。

一般解决方案:

df.loc[<row name>, [<list of col names>]] = [<list of vals>]

您的具体解决方案:

tempSummary.loc[name, ['Wins', 'Singles', 'Doubles', 'Triples', 'Quads', 'Raw Score', 'Total Score']] = [wins, singles, dubs, trips, quads, rawScore, tempTotal]

任何时候.at都使用它几乎总是更好用.loc


推荐阅读