gpt4 book ai didi

python - 从 DataFrame 中读取逗号分隔的序列到 Python 中的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:20 26 4
gpt4 key购买 nike

我有一个 DataFrame df,它有一列 [Main] 并且看起来像这样:

[Main]
Label1_Dim=
Label1_Formula= PP
Label2_Name= Customer
Label2_Value= Tech Service, INC
Label2_Dim=

我要存线Label2_Value= Tech Service, INC 在一个字符串中,更准确地说只是
Tech Service, INC 部分。

pos_customer=df[df['[Main]'] == 'Label2_Name= Customer']
pos_customer_index = pos_customer.index
customer = df.iloc[pos_customer.index[0]+1]['[Main]']

customer=customer[13:]

我的代码找到上一行,将下一行存储在一个字符串中并去除前 13 个字符,这将导致 customer = "Tech Service, INC"

但是逗号好像有问题。通常这段代码对我有用,但在带有逗号的一行中,它只是跳过它并转到 Label2_DIM= 而不是。我不知道为什么,我也尝试了 python split()-method 但我没有解决它。

希望大家帮帮我。

最佳答案

如果我理解你的问题,那么下面的内容应该适合你。

示例数据框:

>>> df
Main
0 Label2_Name= Customer
1 Label2_Value= Tech Service, INC

假设您只需要 = 之后的字符串,然后使用 regex 尝试使用 replace 方法,如下所示:

>>> df.Main.replace(r'.*=', '', regex=True)
0 Customer
1 Tech Service, INC
Name: Main, dtype: object

如果您想要替换特定的 (Label2_Value= Tech Service, INC) 行,则:

>>> df.Main.replace(r'^Label2_Value=', '', regex=True)
0 Label2_Name= Customer
1 Tech Service, INC <--- here it is
Name: Main, dtype: object

没有正则表达式只是用replace:

>>> df.Main.replace('Label2_Value= Tech Service, INC', 'Tech Service, INC')
0 Label2_Name= Customer
1 Tech Service, INC
Name: Main, dtype: object

关于python - 从 DataFrame 中读取逗号分隔的序列到 Python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53442489/

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