Pandas 在数据帧内的指定字符之后删除部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/23767376/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas delete parts of string after specified character inside a dataframe
提问by jonas
I would like a simple mehtod to delete parts of a string after a specified character inside a dataframe. Here is a simplified example:
我想要一个简单的方法来删除数据帧内指定字符之后的部分字符串。这是一个简化的示例:
df:
df:
   obs         a  b  c  d
0    1   1-23-12  1  2  3
1    2  12-23-13  4  5  5
2    3  21-23-14  4  5  5
I would like to remove the parts in the a column after the first - sign, my expected output is:
我想在第一个 - 符号之后删除 a 列中的部分,我的预期输出是:
newdf:
新的:
   obs   a  b  c  d
0    1   1  1  2  3
1    2  12  4  5  5
2    3  21  4  5  5
回答by joemar.ct
You can reformat the values by passing a reformatting function into the applymethod as follows: 
您可以通过将重新格式化函数传递给apply方法来重新格式化值,如下所示:
from StringIO import StringIO
import pandas as pd
data = """   obs  a  b  c  d
1   1-23-12  1  2  3
2  12-23-13  4  5  5
3  21-23-14  4  5  5"""
# Build dataframe from data
df = pd.read_table(StringIO(data), sep='  ')
# Reformat values for column a using an unnamed lambda function
df['a'] = df['a'].apply(lambda x: x.split('-')[0])
This gives you your desired result:
这会给你你想要的结果:
   obs   a  b  c  d
0    1   1  1  2  3
1    2  12  4  5  5
2    3  21  4  5  5

