[英]Python 3.6: Find first occurance string(entire column value) from dataframe which starts with '$'
[英]replace text string in entire column after first occurance
我正在尝试替换整个列中除第一次出现的文本字符串之外的所有内容。 我的具体情况是用看起来像 client_19_Aug_21_22_2022 的数据中的句点替换下划线,我需要它是 client_19.Aug.21.22.2022
if I use [1], I get this error: string index out of range
but [:1] does all occurrences (it doesn't skip the first one)
[1:] inserts . after every character but doesn't find _ and replace
df1['Client'] = df1['Client'].str.replace('_'[:1],'.')
不是最简单的,而是解决方案:
import re
df.str.apply(lambda s: re.sub(r'^(.*?)\.', r'\1_', s.replace('_', '.')))
在 lambda function 中,我们首先将所有_
替换为.
. 然后我们替换第一次出现的.
回到_
。 最后,我们将 lambda 应用于列中的每个值。
Pandas Series
具有.map
方法,您可以使用该方法将任意 function 应用于系列中的每一行。
在您的情况下,您可以编写自己的replace_underscores_except_first
function,如下所示:
def replace_underscores_except_first(s):
newstring = ''
# Some logic here to handle replacing all but first.
# You probably want a for loop with some conditional checking
return newstring
然后将其传递给.map
,如:
df1['Client'] = df1['Client'].map(replace_underscores_except_first)
使用 map 的示例,并在 function 中检查字符串是否包含下划线。 如果是,则拆分它,然后用点将除第一个部分之外的所有部分连接起来。
import pandas as pd
items = [
"client_19_Aug_21_22_2022",
"client123"
]
def replace_underscore_with_dot_except_first(s):
if "_" in s:
parts = s.split("_")
return f"{parts[0]}_{'.'.join(parts[1:])}"
return s
df1 = pd.DataFrame(items, columns=["Client"])
df1['Client'] = df1['Client'].map(replace_underscore_with_dot_except_first)
print(df1)
Output
Client
0 client_19.Aug.21.22.2022
1 client123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.