相关疑难解决方法(0)

grep一个文件,但显示几个周围的行?

我想要grep一个字符串,但也显示前面的五行和以下五行以及匹配的行.我怎么能这样做?

search logging grep command-line-interface

3277
推荐指数
14
解决办法
104万
查看次数

将csv加载到带有numpy的2D矩阵中进行绘图

鉴于此CSV文件:

"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
Run Code Online (Sandbox Code Playgroud)

我只想将它作为矩阵/ ndarray加载3行和7列.但是,出于某种原因,我可以摆脱numpy的是一个有3行(每行一个)而没有列的ndarray.

r = np.genfromtxt(fname,delimiter=',',dtype=None, names=True)
print r
print r.shape

[ (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291111964948.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291113113366.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291120650486.0)]
(3,)
Run Code Online (Sandbox Code Playgroud)

我可以手动迭代并将其破解成我想要的形状,但这看起来很傻.我只是想把它作为一个合适的矩阵加载,这样我就可以将它切成不同的尺寸并绘制它,就像在matlab中一样.

python csv arrays numpy reshape

69
推荐指数
2
解决办法
16万
查看次数

如果您使用'with'语句打开文件,是否仍需要关闭文件对象?

对于打开文件,我习惯了显然较旧的语法:

f = open("sub_ranks.txt","r+")
for line in f:
    ...
f.close()
Run Code Online (Sandbox Code Playgroud)

我被告知现在使用这种语法几次...

with open("sub_ranks.txt", "r+") as f:
    for line in f:
        ...
Run Code Online (Sandbox Code Playgroud)

在使用"with"语句时,第二个示例中仍然需要文件对象"close"语句吗?

如果是这样,是否有任何具体的理由使用"with"语句进行文件读取?在这种情况下,它(稍微)更冗长.

python import file

11
推荐指数
1
解决办法
6543
查看次数

Should I use `with open(file):` if I `pd.read_csv`?

Context

I've learned that one should use with open when reading files in Python:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
Run Code Online (Sandbox Code Playgroud)

(source)

However, I've seen multiple examples where this structure is not used when using pandas' pd.read_csv: …

python csv file-io pandas

4
推荐指数
1
解决办法
1054
查看次数