pandas矢量化字符串替换为索引

时间:2014-06-07 21:05:55

标签: python pandas

尝试更改pandas列字符串中的前两个字符。

def shift(x):
x=list(x)
x[0] = '1'
x[1] = '9'
print x  #this prints the correct result as list
##str(x)
return ''.join(x)  ## this works
mc_data['timeshift'] = mc_data['realtime'].map(lambda x: shift(x) )

输出为NoneType

我也尝试过,str.slice_replace.map(lambda x: '19')

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以构建新字符串,而不是替换前两个字符:

>>> df = pd.DataFrame({"A": ['abcd']*4})
>>> df
      A
0  abcd
1  abcd
2  abcd
3  abcd
>>> df["A"] = "19" + df["A"].str[2:]
>>> df
      A
0  19cd
1  19cd
2  19cd
3  19cd
相关问题