【问题标题】:Python add index number behind stringPython在字符串后面添加索引号
【发布时间】:2021-06-20 15:18:11
【问题描述】:

有没有办法在另一列的字符串后面添加索引号?我已经尝试过使用 df.index ,但后来我收到 ValueError:值长度(0)与索引长度(4)不匹配的错误。或者这个错误TypeError: Index does not support mutable operations.

df = df.reset_index(drop=True)
index = df.index
  
dier = 'BRUINVIS-' + index
df['dier'] = dier

错误:

ValueError: Length of values (2) does not match length of index (4)

【问题讨论】:

  • 请说得更准确些。显示示例、预期输出以及您获得的输出。如果我们不能正确理解问题,我们将无法帮助您
  • 对不起,我要在这里写我的代码:df = df.reset_index(drop=True) index = df.index dier = 'BRUINVIS-' + index df['dier'] = dier这是我得到的错误:ValueError:值的长度(2)与索引的长度(4)不匹配

标签: python pandas string indexing numbers


【解决方案1】:

你的意思是这样吗?

import pandas as pd
df = pd.DataFrame({'column_1':['row', 'row', 'row']})
print(df)
df['column_1'] = df['column_1'] + df.index.astype(str)
print(df)

      column_1
    0      row
    1      row
    2      row
      column_1
    0     row0
    1     row1
    2     row2

【讨论】:

    【解决方案2】:
    df.index = ['BRUINVIS-' + idx for idx in df.index]
    

    【讨论】:

    • 谢谢!但现在我得到这个错误 TypeError: can only concatenate str (not "int") to str
    • df.index = ['BRUINVIS-' + str(idx) for idx in df.index]
    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2021-11-11
    相关资源
    最近更新 更多