首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >大熊猫数据帧中的字符串列操作

大熊猫数据帧中的字符串列操作
EN

Stack Overflow用户
提问于 2015-03-16 16:06:11
回答 1查看 9K关注 0票数 4

我在这样的数据帧中有一个字符串列(Time)。我想在数字之间加上下划线,然后删除月份。

代码语言:javascript
复制
Time
2- 3 months          
1- 2 months          
10-11 months          
4- 5 months
 Desired output:
2_3           
1_2           
10_11           
4_5 

这是我正在尝试的,但似乎不起作用。

代码语言:javascript
复制
def func(string):
    a_new_string =string.replace('- ','_')
    a_new_string1 =a_new_string.replace('-','_')
    a_new_string2= a_new_string1.rstrip(' months')
    return a_new_string2

并将功能应用到数据帧中。

代码语言:javascript
复制
df['Time'].apply(func)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-16 16:09:09

一种选择是使用3个str replace调用:

代码语言:javascript
复制
In [18]:

df['Time'] = df['Time'].str.replace('- ', '_')
df['Time'] = df['Time'].str.replace('-', '_')
df['Time'] = df['Time'].str.replace(' months', '')
df
Out[18]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5

我认为您的问题可能是您没有将apply的结果分配回来:

代码语言:javascript
复制
In [21]:

def func(string):
    a_new_string =string.replace('- ','_')
    a_new_string1 =a_new_string.replace('-','_')
    a_new_string2= a_new_string1.rstrip(' months')
    return a_new_string2

df['Time'] = df['Time'].apply(func)
df
Out[21]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5

你也可以把它做成一个衬里:

代码语言:javascript
复制
In [25]:

def func(string):
    return string.replace('- ','_').replace('-','_').rstrip(' months')

df['Time'] = df['Time'].apply(func)
df
Out[25]:
    Time
0    2_3
1    1_2
2  10_11
3    4_5
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29081530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档