pra*_*dav 6 python regex pandas
我有一个包含所有列中的关键字和值的数据框.请参阅下面的示例.

我想将regex应用于所有列.所以我使用for循环并应用正则表达式:
for i in range (1,maxExtended_Keywords):
temp = 'extdkey_' + str(i)
Extended_Keywords[temp] = Extended_Keywords[temp].str.extract(":(.*)",expand=True)
Run Code Online (Sandbox Code Playgroud)
我得到了理想的最终结果.没问题.

然而,只是古玩是有一种pythonic方式将正则表达式应用于整个数据帧而不是使用for循环并应用于列.
谢谢,
使用pandas.DataFrame.replace与regex=True
df.replace('^.*:\s*(.*)', r'\1', regex=True)
Run Code Online (Sandbox Code Playgroud)
请注意,我的模式使用括号来捕获 之后的部分,':'并使用原始字符串r'\1'来引用该捕获组。
df = pd.DataFrame([
[np.nan, 'thing1: hello'],
['thing2: world', np.nan]
], columns=['extdkey1', 'extdkey2'])
df
extdkey1 extdkey2
0 NaN thing1: hello
1 thing2: world NaN
Run Code Online (Sandbox Code Playgroud)
df.replace('^.*:\s*(.*)', r'\1', regex=True)
extdkey1 extdkey2
0 NaN hello
1 world NaN
Run Code Online (Sandbox Code Playgroud)