我正在尝试实现最简单的任务-创建如下所示的FISCAL_YEAR列(列YEAR给出):
+------+-------------+
| YEAR | FISCAL_YEAR |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
我一直得到错误:can only concatenate str (not "int") to str
这些是我目前为止尝试过的步骤,没有成功:
df['fiscal_year'] = str(df['year']) + "-" + str(df['year']+1)
df['fiscal_year'] = df['year'].astype(str) + "-" + (df['year']+1).astype(str)
df['year_str'] = pd.Series(df['year'], dtype=pd.StringDtype())
也:
df['year_str'] = df['year'].astype(str)
然后:
df['year_str'].str.cat(df['year_str'].astype(int) + 1, sep='-')
这些选项都不起作用。我还遗漏了什么吗?
**我在Windows 10和Python版本3.9.7
一个万无一失的方法可能是:
df['FISCAL_YEAR'] = (df['YEAR'].astype(str)
+'-'+
df['YEAR'].astype(int).add(1).astype(str)
)
输出:
YEAR FISCAL_YEAR
0 2022 2022-2023
1 2022 2022-2023
2 2022 2022-2023
3 2022 2022-2023