df=pd.read_excel('Canada.xlsx',sheet_name='Canada by Citizenship',skiprows=range(20),skipfooter=2)
df['Total']=df.iloc[:,'1980':'2013'].sum(axis=1)
这是我收到的错误:
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1980] of <class 'str'>
我从这个 link 收到了数据集
最佳答案
列是整数。你可以切片:
df.loc[:, range(1980, 2014)].sum(1)
# or
df.iloc[:, df.columns.get_loc(1980):df.columns.get_loc(2013)+1].sum(1)
0 58639
1 15699
2 69439
3 6
4 15
...
190 97146
191 2
192 2985
193 1677
194 8598
Length: 195, dtype: int64
关于python - 当我尝试对 pandas 数据框中的多列求和时,为什么会收到错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57694956/