“Cast doesn’t work as expected when concatenating strings.”

huangapple go评论67阅读模式
英文:

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:

  1. df['fiscal_year'] = str(df['year']) + "-" + str(df['year']+1)

  2. 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:

  1. df['fiscal_year'] = str(df['year']) + "-" + str(df['year']+1)

  2. 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

huangapple
  • 本文由 发表于 2023年4月6日 22:54:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定