【问题标题】:Trying to concat a string and an int in another column试图在另一列中连接一个字符串和一个 int
【发布时间】:2021-09-01 17:28:40
【问题描述】:

我在尝试创建基于另外 2 列的列时遇到问题。

所以我有一个如下所示的数据框:

ID Number
18957585-4 3
14548291-2 2
13553585-8 6
2454841-0 21
48536515-6 40
14548291-2 33

我想创建一个新列,将这两者结合起来,如下所示:

ID Number New_Column
18957585-4 3 18957585-43
14548291-2 2 14548291-22
13553585-8 6 13553585-86
2454841-0 21 2454841-021
48536515-6 40 48536515-640
14548291-2 33 14548291-233

我试过了

df['New_Column'] = df['ID'] + str(df['Number'])

但这不起作用,结果是一个有 4 个数字的单元格,每个数字都在单元格的角落。如果我双击它,它会说: " 2 36 3 名称:ID_Par,数据类型:int64"

我也试过

df['New_Column'] = str(df['ID']) + str(df['Number'])

但这也不起作用。我使用 pyodbc 从 SQL 查询中获得了数据帧“df”,如果这有所不同的话。

希望有人能帮帮我,谢谢

【问题讨论】:

    标签: python string integer concatenation


    【解决方案1】:

    尝试使用astype 方法转换数字列:

    df['New_Column'] = df['ID'] + df['Number'].astype(str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2018-10-15
      • 1970-01-01
      相关资源
      最近更新 更多