简体   繁体   English

Pandas在数据帧内删除指定字符后的部分字符串

[英]Pandas delete parts of string after specified character inside a dataframe

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: newdf:

   obs   a  b  c  d
0    1   1  1  2  3
1    2  12  4  5  5
2    3  21  4  5  5

You can reformat the values by passing a reformatting function into the apply method 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pandas 删除指定字符序列后的部分字符串 - Pandas remove parts of string after specified character sequence 如何删除 Pandas Dataframe 列中所有值的字符串的最后一个字符? - How to delete the last character of a string for all values in a Pandas Dataframe column? 删除熊猫数据框中的字符串 - delete string in a pandas dataframe pandas/regex: 去掉连字符或括号字符后的字符串(包括) carry string in the comma after the comma in pandas dataframe - pandas/regex: Remove the string after the hyphen or parenthesis character (including) carry string after the comma in pandas dataframe 在熊猫数据框内拆分字符串 - Splitting string inside pandas dataframe 使用条件在熊猫的一个数据框中移动多个部分 - Shift several parts inside one dataframe in pandas with condition 遍历 Pandas DataFrame 中的行,删除特定字符串后指定列数内的所有值 - Iterate Over Rows in Pandas DataFrame Deleting All Values Within a Specified Number of Columns After a Specific String 删除熊猫数据框中特定字符后的值 - Remove value after specific character in pandas dataframe 通过在字符串中查找字符来对熊猫数据框进行切片 - Slicing pandas dataframe by looking for character “in” string 在 pandas dataframe 中有效地搜索字符串的第一个字符 - Efficiently search for first character of a string in a pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM