如何从 .xlsx 文件创建具有多个空格作为分隔符的 .dat 文件
How to create .dat file with multiple spaces as delimiter from .xlsx file
我有一个 xlsx 文件,其中每一行对应一个样本,每一列都有相关的特征,如下所示:
xlsx file example
我正在尝试将此 xlsx 文件转换为 dat 文件,用多个空格分隔列,如下例所示:
samples property feature1 feature2 feature3
sample1 3.0862 0.8626 0.7043 0.6312
sample2 2.8854 0.7260 0.7818 0.6119
sample3 0.6907 0.4943 0.0044 0.4420
sample4 0.9902 0.0106 0.0399 0.9877
sample5 0.7242 0.0970 0.3199 0.5504
我尝试通过在 pandas 中创建一个数据框并使用 dataframe.to_csv 将文件另存为 .dat 来实现这一点,但它只允许我使用一个字符作为分隔符。有谁知道我如何创建一个像上面那样的文件?
您可以使用数据框的字符串表示 to_string
,由 pandas 从 Excel:
导入
df = pd.read_excel('input.xlsx')
with open ('output.dat', 'w') as f:
f.write(df.to_string(index=False))
这是另一种不使用 DataFrame
的方法。我们将拥有更大的灵活性,因为我们自己从头开始构建所有结构。
假设你读取了xlsx文件,并以二维列表的形式存储如下:
lines = [['sample1', 3.0862, 0.8626, 0.7043, 0.6312],
['sample2', 2.8854, 0.7260, 0.7818, 0.6119],
['sample3', 0.6907, 0.4943, 0.0044, 0.4420],
['sample4', 0.9902, 0.0106, 0.0399, 0.9877],
['sample5', 0.7242, 0.0970, 0.3199, 0.5504]]
我们可以使用 ljust
、rjust
或 center
等字符串方法。在这里,我只是向您展示以长度作为第一个参数的 ljust
的用法。长度将是左对齐的总宽度。
也可以使用 f-string 以 f'{var:^10.4f}'
的格式进行填充。各个组成部分的含义是:
^
表示居中(可改为<
左对齐或>
右对齐)
10
是填充长度
.4
是小数位数
f
表示浮动
所以,这是最终的脚本。
padding1 = 12
padding2 = 10
print('samples'.ljust(padding1 + 1) + 'property ' + 'feature1 ' + 'feature2 ' + 'feature3')
for line in lines:
text = line[0].ljust(padding1)
for i in range(1, len(line)):
text += f'{line[i]:^{padding2}.4f}'
print(text)
我有一个 xlsx 文件,其中每一行对应一个样本,每一列都有相关的特征,如下所示: xlsx file example
我正在尝试将此 xlsx 文件转换为 dat 文件,用多个空格分隔列,如下例所示:
samples property feature1 feature2 feature3
sample1 3.0862 0.8626 0.7043 0.6312
sample2 2.8854 0.7260 0.7818 0.6119
sample3 0.6907 0.4943 0.0044 0.4420
sample4 0.9902 0.0106 0.0399 0.9877
sample5 0.7242 0.0970 0.3199 0.5504
我尝试通过在 pandas 中创建一个数据框并使用 dataframe.to_csv 将文件另存为 .dat 来实现这一点,但它只允许我使用一个字符作为分隔符。有谁知道我如何创建一个像上面那样的文件?
您可以使用数据框的字符串表示 to_string
,由 pandas 从 Excel:
df = pd.read_excel('input.xlsx')
with open ('output.dat', 'w') as f:
f.write(df.to_string(index=False))
这是另一种不使用 DataFrame
的方法。我们将拥有更大的灵活性,因为我们自己从头开始构建所有结构。
假设你读取了xlsx文件,并以二维列表的形式存储如下:
lines = [['sample1', 3.0862, 0.8626, 0.7043, 0.6312],
['sample2', 2.8854, 0.7260, 0.7818, 0.6119],
['sample3', 0.6907, 0.4943, 0.0044, 0.4420],
['sample4', 0.9902, 0.0106, 0.0399, 0.9877],
['sample5', 0.7242, 0.0970, 0.3199, 0.5504]]
我们可以使用 ljust
、rjust
或 center
等字符串方法。在这里,我只是向您展示以长度作为第一个参数的 ljust
的用法。长度将是左对齐的总宽度。
也可以使用 f-string 以 f'{var:^10.4f}'
的格式进行填充。各个组成部分的含义是:
^
表示居中(可改为<
左对齐或>
右对齐)10
是填充长度.4
是小数位数f
表示浮动
所以,这是最终的脚本。
padding1 = 12
padding2 = 10
print('samples'.ljust(padding1 + 1) + 'property ' + 'feature1 ' + 'feature2 ' + 'feature3')
for line in lines:
text = line[0].ljust(padding1)
for i in range(1, len(line)):
text += f'{line[i]:^{padding2}.4f}'
print(text)