<p>使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">^{<cd1>}</a>重塑形状。好处是它会自动创建一个<code>'home_or_away'</code>指示符,但我们将首先更改列,使它们成为“score\u home”(而不是“home\u score”)</p>
<pre><code># Swap column stubs around `'_'`
df.columns = ['_'.join(x[::-1]) for x in df.columns.str.split('_')]
# Your code to filter, would drop everything in your provided example
# df['date'] = pd.to_datetime(df['date'])
# df[df['date'].dt.year.gt(2010) & df['tournament'].ne('Friendly')]
df = pd.wide_to_long(df, i='date', j='home_or_away',
stubnames=['team', 'score'], sep='_', suffix='.*')
# country neutral tournament city team score
#date home_or_away
#1872-11-30 home Scotland False Friendly Glasgow Scotland 0
#1873-03-08 home England False Friendly London England 4
#1874-03-07 home Scotland False Friendly Glasgow Scotland 2
#...
#1878-03-02 away Scotland False Friendly Glasgow England 2
#1878-03-23 away Scotland False Friendly Glasgow Wales 0
#1879-01-18 away England False Friendly London Wales 1
</code></pre>
<p>所以现在无论是主场还是客场,你都可以得到分数:</p>
<pre><code>df.groupby('team')['score'].sum()
#team
#England 12
#Scotland 34
#Wales 1
#Name: score, dtype: int64
</code></pre>