在python datafram中用新的结尾替换单词的结尾

2024-06-03 03:02:55 发布

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

我有一个充满法语单词、结尾和新结尾的数据框。我想创建一个第四列,用以下替代词:

word   |ending|new ending|what i want|
--------------------------------------
placer |cer   |ceras     |placeras   |
placer |cer   |cerait    |placerait  |
placer |cer   |ceront    |placeront  |
finir  |ir    |iras      |finiras    |

所以基本上,在第1栏中,用第3栏中的内容来替换第2栏中的等价内容。你知道吗

有什么想法吗?你知道吗


Tags: 数据内容new结尾ending单词whatword
3条回答

下面是另一个解决方案:

df.word.replace(df.ending, '', regex=True).str.cat(df["new ending"].astype(str))

以及输出:

0     placeras
1    placerait
2    placeront

使用^{}

df['new_word'] = df.apply(
    lambda row: row['word'].replace(row['ending'], row['new ending']),
    axis=1
)
#     word ending new ending   new_word
#0  placer    cer      ceras   placeras
#1  placer    cer     cerait  placerait
#2  placer    cer     ceront  placeront
#3   finir     ir       iras    finiras

正如@jpp所指出的,这种方法需要注意的是,如果结尾出现在字符串的中间,它将无法正常工作。你知道吗

在这种情况下,请参阅this post,了解如何替换字符串末尾的内容。你知道吗

下面是使用.loc访问器的一种方法:

import pandas as pd

df = pd.DataFrame({'word': ['placer', 'placer', 'placer'],
                   'ending': ['cer', 'cer', 'cer'],
                   'new_ending': ['ceras', 'cerait', 'ceront']})

df['result'] = df['word']
df['lens'] = df['ending'].map(len)

df.loc[pd.Series([i[-j:] for i, j in zip(df['word'], df['lens'])]) == df['ending'], 'result'] = \
pd.Series([i[:-j] for i, j in zip(df['word'], df['lens'])]) + df['new_ending']

df = df[['word', 'ending', 'new_ending', 'result']]

#      word ending new_ending     result
# 0  placer    cer      ceras   placeras
# 1  placer    cer     cerait  placerait
# 2  placer    cer     ceront  placeront

相关问题 更多 >