【问题标题】:Indexing a string in python在python中索引一个字符串
【发布时间】:2018-04-24 15:18:42
【问题描述】:

行等于下面。 PIC_loc = 23;我想要 42 和 42 之后的 15 位。输出应该是 42011721930018984

                                            PIC_1  p_lgth  Wgt
**PARTIAL-DECODE***P / 42011721930018984390078...      53  112

Output = row['PIC_1'][PIC_loc:PIC_loc+15]

上面的代码给出了这个错误信息

TypeError: cannot do slice indexing on    
class 'pandas.core.indexes.range.RangeIndex'> with these indexers [2    23
Name: PIC_1, dtype: int64] of <class 'pandas.core.series.Series'>

【问题讨论】:

  • PIC_1 是一个字符串;它是以“**PARTIAL”开头并以“0078...”结尾的整行
  • 当你昨天问这个问题时,Joran Beasley 在评论中给了你一个尝试的解决方案,即fifteencharactersfollowing42 = a_string.split("42",1)[-1][:15]。那没有用吗?如果PIC_1 是您描述的字符串,它对我来说很好。
  • 给出消息“KeyError:-1”

标签: python pandas


【解决方案1】:

row['PIC_1'] 返回一个 Pandas 系列,因此您需要先访问这些值,然后才能对它们进行切片。您正在寻找对字符串进行切片以便可以使用pandas.Series.str 向量化字符串方法:

row['PIC_1'].str[PIC_loc:PIC_loc+15]

【讨论】:

  • 试过这个并得到 NAN 作为输出值
  • row['PIC_1'] 返回什么?
  • row['PIC_1'] **PARTIAL-DECODE***P / 42011721930018984390078... Name: PIC_1, dtype: object
  • 不知道为什么这不起作用。我正在将您的数据重新创建为pd.Series(['**PARTIAL-DECODE***P / 42011721930018984390078']).str[23:23+17],效果很好。
  • 感谢您的尝试
猜你喜欢
  • 2015-08-24
  • 2015-04-23
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
相关资源
最近更新 更多