英文:
Cast doesn't work as expected when concatenating strings
问题
I am trying to achieve the simplest task - creating the FISCAL_YEAR column as shown below (column YEAR is given):
+------+-------------+
| YEAR | FISCAL_YEAR |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
I keep getting the error: can only concatenate str (not "int") to str
These are the steps I've tried so far, without success:
-
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())
And also:
df['year_str'] = df['year'].astype(str)
And then:
df['year_str'].str.cat(df['year_str'].astype(int) + 1, sep='-')
None of these options work. Is there is anything else I'm missing?
** I am on Windows 10 and Python version 3.9.7
英文:
I am trying to achieve the simplest task - creating the FISCAL_YEAR column as shown below (column YEAR is given):
+------+-------------+
| YEAR | FISCAL_YEAR |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
| 2022 | 2022-2023 |
+------+-------------+
I keep getting the error: can only concatenate str (not "int") to str
These are the steps I've tried so far, without success:
-
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())
And also:
df['year_str'] = df['year'].astype(str)
And then:
df['year_str'].str.cat(df['year_str'].astype(int) + 1, sep='-')
None of these options work. Is there is anything else I'm missing?
** I am on Windows 10 and Python version 3.9.7
答案1
得分: 1
以下是您要翻译的代码部分:
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
英文:
A failproof way could be:
df['FISCAL_YEAR'] = (df['YEAR'].astype(str)
+'-'+
df['YEAR'].astype(int).add(1).astype(str)
)
Output:
YEAR FISCAL_YEAR
0 2022 2022-2023
1 2022 2022-2023
2 2022 2022-2023
3 2022 2022-2023
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论