gpt4 book ai didi

python - 使用正则表达式从 Pandas 数据框中的列中提取数据

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:11 32 4
gpt4 key购买 nike

我有一个数据框 df 定义如下

import pandas as pd
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Hello Kitty how=1234 when=2345",
"how=3456 Hello Puppy when=7685",
"how=646 It is an Helloexample when=9089",
"for how=6574 stackoverflow when=5764",
"Hello when=3632 World how=7654",
],
}
)





df
Out[100]:
ID name
0 1 Hello Kitty how=1234 when=2345
1 2 how=3456 Hello Puppy when=7685
2 3 how=646 It is an Helloexample when=9089
3 4 for how=6574 stackoverflow when=5764
4 5 Hello when=3632 World how=7654

我想将 howwhen 之后写入的值提取到两个单独的列 how 和 when 中。我怎样才能使用正则表达式做同样的事情?

例如:在第一条记录中,我应该在 how 列中得到 1234,在 when 列中得到 2345。在最后一条记录中,我应该在 how 列中得到 7654 ,在 when

列中得到 3632

最佳答案

使用str.extract

例如:

df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Hello Kitty how=1234 when=2345",
"how=3456 Hello Puppy when=7685",
"how=646 It is an Helloexample when=9089",
"for how=6574 stackoverflow when=5764",
"Hello when=3632 World how=7654",
],
}
)
df['when'] = df['name'].str.extract(r"when=(\w+)") #If only int use `(\d+)`
df['how'] = df['name'].str.extract(r"how=(\w+)") #If only int use `(\d+)`
print(df)

输出:

   ID                                     name  when   how
0 1 Hello Kitty how=1234 when=2345 2345 1234
1 2 how=3456 Hello Puppy when=7685 7685 3456
2 3 how=646 It is an Helloexample when=9089 9089 646
3 4 for how=6574 stackoverflow when=5764 5764 6574
4 5 Hello when=3632 World how=7654 3632 7654

关于python - 使用正则表达式从 Pandas 数据框中的列中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065078/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com