我正在尝试按如下方式更新(pandas 数据框的)列值:
1234(456 应该变成 1234
abcde(fg 应该变成 abcde
我写了下面的代码,但由于某些原因它不工作:
energy[(energy['Country'].str.contains('\(')) &
(energy['Country'] != np.NAN)
].apply(lambda x: x['Country'].split('(')[0])
这是错误:ValueError: cannot index with vector containing NA/NaN values
有什么想法可以改进我的代码并使其正常工作吗?
请您参考如下方法:
试试这个:
In [23]: df
Out[23]:
Country
0 1234(456)
1 abcde(fg xxxx
In [24]: df.Country.str.replace(r'([^\(]*).*', r'\1')
Out[24]:
0 1234
1 abcde
Name: Country, dtype: object
