使用Python删除数据帧中所有后跟特定字符

2024-05-29 02:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个特定字符的列表,我们需要删除它后面的所有字符

输入数据:

  text_dir
abc School, Uk
xyz College, USA
Pqr University, Berlin

所需的输出值:

  text_dir
abc School
xyz College
Pqr University

代码段:

spl_character=['School', 'college', 'university']
df['text_dir'] = df['text_dir'].str.split(spl_character).str[0]

Gives Error:
TypeError: unhashable type: 'list'

Tags: 数据textdf列表dir字符splabc
3条回答

我修改了你的输入并试图解决这个问题,我已经用正则表达式解决了这个问题

import pandas as pd
import re


text_dir = ["abc School, Uk", "xyz College, USA", "Pqr University, Berlin"]
spl_character=['School,', 'College,', 'University,']


df = pd.DataFrame()
df['text_dir'] = text_dir


final_list = []

for item in df.text_dir:
    for character in spl_character:
        if j in i.split(' '):
            val_re = re.compile("^(.*)"+character+"")
            val_match = val_re.search(item)
            final_list.append(val_match.group())

df['text_dir'] = final_list

输出:

    text_dir
0   abc School,
1   xyz College,
2   Pqr University,

IIUC:

pat = f'(?i)^(.*)({"|".join(spl_character)}).*$'
df.text_dir.str.replace(pat, r'\1\2', regex=True)

0        abc School
1       xyz College
2    Pqr University
Name: text_dir, dtype: object
import pandas as pd

text_dir = ["abc School, Uk", "xyz College, USA", "Pqr University, Berlin"]
df = pd.DataFrame()
df['text_dir'] = text_dir
      text_dir
0   abc School, Uk
1   xyz College, USA
2   Pqr University, Berlin

使用lambda函数

# Reformat values for column "text_dir" using a lambda function
df['text_dir'] = df['text_dir'].apply(lambda x: x.split(',')[0])

输出

    text_dir
0   abc School
1   xyz College
2   Pqr University

相关问题 更多 >

    热门问题