gpt4 book ai didi

python - 从 .csv 文件中提取数值

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

我有一个数据框,其中包含一列路径名。我可以使用以下方式访问这些路径:

for i, p in enumerate(df['path']):

但是,我现在希望从每个输出文件中提取一个值。

csv 文件如下所示:

# some values 
# some values : some values
# some values : some values
# some values : some values
# some string : the value I want
# some string : some values

有没有办法提取这个值并将其插入到我的数据框中?

我相信正则表达式可以解决问题。我只是不确定具体的方法。我有一些模板代码,如下所示:

if re.match(r"something", p):
df = pd.read_csv(p)
df.iloc[i, value_column] = the value I want

最佳答案

这是使用内置 split 从 text/csv 中提取值的解决方案:

def get_value(string):
array = string.split(": ") # maybe without the white space
return array[0] if len(array) == 1 else array[1]

get_value('some values')
# 'some values'
get_value('some string : the value I want')
# 'the value I want'

或者,使用正则表达式

re.sub(r'.*\:\s*(.*)', r'\1', 'some values')
# 'some values'
re.sub(r'.*\:\s*(.*)', r'\1', 'some string : the value I want')
# 'the value I want'

关于python - 从 .csv 文件中提取数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58155442/

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