我有两个文件,每个文件大小相同(100x12),包含用逗号分隔的正负数值。
文件1的输出示例:
-14.99,-15.6,8.0 ->
-9.0,34.87,98.98 ->
(and so on)文件2的输出示例:
-15.99,-18.6,8.00 ->
-3.0,34.34,-98.88 ->
(and so on)我试过了:
awk '{getline t<"file1"; print $0-t}' file2但是,这只减去了第一列。如何将其扩展为从file2/column2 2中以数字方式减去file1/column2 n1?
我对使用pandas执行此操作持开放态度。提前谢谢你!
发布于 2019-03-05 05:16:20
首先是数据
file1 = """
-14.99,-15.6,8.0 ->
-9.0,34.87,98.98 ->
"""
file2 = """
-15.99,-18.6,8.00 ->
-3.0,34.34,-98.88 ->
"""
from io import StringIO # faking file on disk熊猫回答。
import pandas as pd
converter = {2: lambda s: float(s.split(' ')[0])}
df1 = pd.read_csv(StringIO(file1), header=None, converters=converter)
df2 = pd.read_csv(StringIO(file2), header=None, converters=converter)
(df1-df2).to_csv('pddiff12.csv', header=False, index=False) 或者使用纯python滚动它。
# cmt 1 -> indent under with-statement
def read_csv(file_name):
#with open('file_name', 'rt') as f1: # uncomment when reading from disk
f1 = StringIO(file_name) # comment out when reading from disk
rows = [r for r in f1.readlines() if r.strip()] # cmt 1
crunch = lambda row: [float(r) for r in row.split(',')]
rows = [crunch(r.split(' ')[0]) for r in rows]
return rows
data1 = read_csv(file1)
data2 = read_csv(file2)
diff = []
for row1, row2 in zip(data1, data2):
diff.append([i-j for i, j in zip(row1, row2)])
with open('diff12.csv', 'wt') as d12:
for row in diff:
d12.write(', '.join((str(v) for v in row)) + '\n')熊猫肯定是最容易阅读和工作的,尽管如果人们倾向于避免这一点,它是一个值得注意的依赖。在这种情况下,我想我不会。
发布于 2019-03-05 04:25:05
在我的头上-所以检查语法!
import numpy as np
with open("file1.txt, "r") as f1:
with open("file2.txt, "r") as f2:
array1 = np.asarray(f1.read().split(','))
array2 = np.asarray(f2.read().split(','))
result = array1 - array2
print([x for x in result])发布于 2019-03-05 04:32:32
在awk中:
$ awk '
NR==FNR { # hash file1 values to a
for(i=1;i<=NF;i++)
a[FNR][i]=$i
next
}{ # process file2, subtract values from file1 respectives
for(i=1;i<=NF;i++)
$i=$i-a[FNR][i]
}1' file1 file1输出:
-1,-3,8.00 ->
6,-0.53,-98.88 ->https://stackoverflow.com/questions/54990884
复制相似问题