
本文介绍如何使用 Python 的 Pandas 库,从 DataFrame 中提取特定行的数据,并将其更新到文本文件中特定标识符(如 "B" 或 "Name2")后的相应位置。通过使用正则表达式,可以灵活地定位和替换文件中的目标数值,即使这些数值不在固定行上也能准确更新。
准备工作:导入必要的库
首先,需要导入 pandas 库来处理 DataFrame,以及 re 库来使用正则表达式进行文本匹配和替换。
import pandas as pd import re
读取数据和定义变量
假设你已经有了一个 Pandas DataFrame df,并且知道要替换的行索引 idx 和要查找的标识符 to_replace。
# 示例 DataFrame
data = {'i': ['unit1', 1000, -3000, -2000, 900],
'j': ['unit2', 100, 200, 90, 40],
'k': ['unit3', 84, 60, 195, 209]}
df = pd.DataFrame(data)
idx = 3 # 要从 DataFrame 中提取的行索引
to_replace = "B" # 要在文件中查找的标识符
input_file = "input_file.txt" #输入文件
output_file = "output_file.txt" #输出文件读取文件内容
打开文本文件,读取其全部内容到一个字符串变量中。
with open(input_file, "r") as f_in:
file_string = f_in.read()从 DataFrame 中提取数值
使用 df.loc 方法,根据行索引 idx 和列名("i", "j", "k")从 DataFrame 中提取要替换的数值。
i, j, k = df.loc[idx, ["i", "j", "k"]]
使用正则表达式进行替换
这是核心步骤。使用 re.sub 函数,结合正则表达式,在 file_string 中查找匹配的内容,并进行替换。
正则表达式解释:
替换字符串解释:
re.M 和 re.S 标志:
file_string = re.sub(
rf"^({to_replace}\s.*?)i = \S+ j = \S+ k = \S+",
f"\g<1>i = {i} j = {j} k = {k}",
file_string,
flags=re.M | re.S,
)将修改后的内容写入文件
打开输出文件,将修改后的 file_string 写入。
with open(output_file, "w") as f_out:
f_out.write(file_string)import pandas as pd
import re
# 示例 DataFrame
data = {'i': ['unit1', 1000, -3000, -2000, 900],
'j': ['unit2', 100, 200, 90, 40],
'k': ['unit3', 84, 60, 195, 209]}
df = pd.DataFrame(data)
idx = 3 # 要从 DataFrame 中提取的行索引
to_replace = "B" # 要在文件中查找的标识符
input_file = "input_file.txt" #输入文件
output_file = "output_file.txt" #输出文件
# 创建示例输入文件
with open(input_file, "w") as f:
f.write("""A first = 4 | 1_3_5_4 Name1
labelToSkip
i = 1000000 j = -3 k = -15
end
B first = 4 | 9_2_2_4 Name2
labelToSkip
i = 150000 j = -3 k = -20
end
""")
with open(input_file, "r") as f_in:
file_string = f_in.read()
i, j, k = df.loc[idx, ["i", "j", "k"]]
file_string = re.sub(
rf"^({to_replace}\s.*?)i = \S+ j = \S+ k = \S+",
f"\g<1>i = {i} j = {j} k = {k}",
file_string,
flags=re.M | re.S,
)
with open(output_file, "w") as f_out:
f_out.write(file_string)
通过结合 Pandas DataFrame 的数据提取功能和正则表达式的灵活匹配能力,可以高效地实现文本文件中特定数值的更新。这种方法适用于处理结构化的文本数据,并能灵活应对不同格式的文件。请务必根据实际情况调整代码,并注意备份和错误处理。
以上就是使用 Pandas DataFrame 数据更新文本文件中特定标识符后的数值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号