如何在Python中将csv文件中的行条目分隔为具有重复标签的不同列?

i7uq4tfw  于 12个月前  发布在  Python
关注(0)|答案(4)|浏览(77)

我需要重新构造一个.csv文件,该文件遵循以下结构:

a b
1 2
3 4
5 6
...

在这个新的结构中:

a b a b a b ...
1 2 3 4 5 6 ...

我不知道如何在不遍历每一行的情况下有效地完成这一任务。在Python中有没有更有效的方法来实现这一点?

5cnsuln7

5cnsuln71#

以下是一个可能的解决方案:

import pandas as pd

# read the .csv to a dataframe
df = pd.read_csv('your_file.csv')

# create a new df
new_df = pd.DataFrame([df.to_numpy().ravel()], columns=df.columns.to_list() * len(df))
print(new_df)

图纸:

a  b  a  b  a  b
0  1  2  3  4  5  6

要保存新的框架,请执行以下操作:

new_df.to_csv("out.csv", index=False)
ufj5ltwl

ufj5ltwl2#

这里有一个纯Python的可能解决方案(不需要像Pandas这样的大人物):

with open('file.csv') as f:
    columns = f.readline().strip().split()
    rows = f.read().strip().split("\n")
    print(' '.join(len(rows) * columns))
    print(' '.join(r.strip() for r in rows))
rbl8hiat

rbl8hiat3#

如果文件是csv格式,即

a,b
1,2
3,4
....

可以使用以下方法

import csv

# Input and output file names
input_file = 'input.csv'
output_file = 'output.csv'

# Reading CSV file
with open(input_file, 'r') as input_file_csv:
    reader = csv.reader(input_file_csv)
    rows = list(reader)
    # [['a', 'b'], ['1', '2'], ['3', '4'], ['5', '6']]

row1 = [item for i in range(len(rows)-1) for item in rows[0]]
# ['a', 'b', 'a', 'b', 'a', 'b']

row2 = [item for i in range(1,len(rows)) for item in rows[i]]
# ['1', '2', '3', '4', '5', '6']

# Write to CSV file
with open(output_file, 'w', newline='') as output_file_csv:
    writer = csv.writer(output_file_csv)
    writer.writerow(row1)
    writer.writerow(row2)
0kjbasz6

0kjbasz64#

使用Pandas,我们可以将其视为对隐含索引进行透视,这通常是我们使用unstack进行的,但在这种情况下,实际上更容易对列进行透视,即stack

import pandas as pd

delimiter = ' '

df = pd.read_csv(filename, sep=delimiter)

# Unstack all rows to one row.
# Actually stacks columns, drops the original index, then turns back into a df.
result = df.stack().droplevel(0).to_frame().T

测试结果:

a  b  a  b  a  b
0  1  2  3  4  5  6

返回CSV:

result.to_csv(new_filename, index=False, sep=delimiter)
a b a b a b
1 2 3 4 5 6

相关问题