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

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

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):

  1. +------+-------------+
  2. | YEAR | FISCAL_YEAR |
  3. +------+-------------+
  4. | 2022 | 2022-2023 |
  5. +------+-------------+
  6. | 2022 | 2022-2023 |
  7. +------+-------------+
  8. | 2022 | 2022-2023 |
  9. +------+-------------+
  10. | 2022 | 2022-2023 |
  11. +------+-------------+

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):

  1. +------+-------------+
  2. | YEAR | FISCAL_YEAR |
  3. +------+-------------+
  4. | 2022 | 2022-2023 |
  5. +------+-------------+
  6. | 2022 | 2022-2023 |
  7. +------+-------------+
  8. | 2022 | 2022-2023 |
  9. +------+-------------+
  10. | 2022 | 2022-2023 |
  11. +------+-------------+

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

以下是您要翻译的代码部分:

  1. df['FISCAL_YEAR'] = (df['YEAR'].astype(str)
  2. + '-' +
  3. df['YEAR'].astype(int).add(1).astype(str)
  4. )

输出:

  1. YEAR FISCAL_YEAR
  2. 0 2022 2022-2023
  3. 1 2022 2022-2023
  4. 2 2022 2022-2023
  5. 3 2022 2022-2023
英文:

A failproof way could be:

  1. df['FISCAL_YEAR'] = (df['YEAR'].astype(str)
  2. +'-'+
  3. df['YEAR'].astype(int).add(1).astype(str)
  4. )

Output:

  1. YEAR FISCAL_YEAR
  2. 0 2022 2022-2023
  3. 1 2022 2022-2023
  4. 2 2022 2022-2023
  5. 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:

确定