将csv文件拆分为两个单独的文件python3.7

2024-09-30 10:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,需要分割成两个csv文件(file1.csv和file2.csv)。应根据列“Name”进行拆分。70%的行需要写入file1.csv,其余30%写入file2.csv。例如,有10行名为“AAA”。所以10行中的70%意味着前7行“AAA”需要写入file1.csv,接下来的3行写入file2.csv。像这样,“Name”列下的所有名称都需要这样做。 如果得到一个十进制数,例如0.7 x 9行=6.3。然后前6行(四舍五入)到file1.csv,其余3行到file2.csv 如何使用Python代码实现这一点?谢谢你https://fil.email/FPYB1RWd


Tags: 文件csv代码namehttps名称emailfile1
3条回答

很简单:制作一个包含记录列表的字典,输入给定列的内容(这里我使用的是第0列),然后循环这些记录 根据OP指定的简单规则,列出并输出包含在两个输出文件之一的记录列表中的每个记录。在

from csv import reader, writer

inp = reader(open(...))
outs = [writer(open(fnm, 'w') for fnm in ('f30', 'f70')]

column, d = 0, {}

for rec in inp0:
    d.setdefault(rec[column], []).append(rec)

for recs in d.values():
    l = round(0.7*len(recs))
    for n, rec in enumerate(recs):
        outs[n<l].writerow(rec)

布尔值是整数的子类,其值为1(当n<l)或0时,可用于索引writers的列表。

下面是使用IPython会话(稍微 编辑以减少空白)和一些人工数据

^{pr2}$

如您所见,第一个文件将获得原始记录的70%,而 第二个得到剩下的30%。在

“” 用你的原始文件名代替你的“文件名” 使用此函数,该函数将拆分csv文件并保存。 您可以更改拆分百分比以获得不同的文件大小 “”

def split_csv("your_file_name.csv"):
    import pandas as pd
    df = pd.read_csv("your_file_name.csv")
    split_percent = 0.7
    df_length = int(len(df)*split_percent)
    df1 = df.iloc[:df_length,:]
    df2 = df.iloc[df_length:,:]
    df1.to_csv("file1.csv")
    df2.to_csv("file2.csv")

读取整个csv文件并将内容存储在一个列表中。然后在临时列表中存储类似的csv数据。存储后,从列表中提取70%的数据并将其写入文件,然后将剩余的数据写入另一个文件。在

csv_data = []
with open ('file.csv') as file:
    csv_data.append(file.read())
csv_data = (''.join(csv_data)).split("\n")
header = csv_data[0]
csv_data = csv_data[1:]
temp_list = []
add_header = True
for i in csv_data:
    if len(temp_list) == 0:
        temp_list.append(i)
    elif i.split(',')[0] == temp_list[0].split(',')[0]:
        temp_list.append(i)
    else:
        file_length = len(temp_list)
        line_count = int((0.7*file_length)+1)
        if line_count == 1:
            with open("file1.csv","a+") as file1:
                if add_header:
                    add_header = False
                    file1.write(header+'\n')
                file1.write(temp_list[0]+'\n')
        else:
            seventy_perc_lines = temp_list[:line_count]
            thirty_perc_lines = temp_list[line_count:]
            if add_header:
                seventy_perc_lines.insert(0,header)
                thirty_perc_lines.insert(0,header)
                add_header = False
            with open("file1.csv","a+") as file1:
                for j in range(len(seventy_perc_lines)):
                    file1.write(seventy_perc_lines[j]+'\n')
            if len(thirty_perc_lines) != 0:
                with open("file2.csv","a+") as file2:
                    for j in range(len(thirty_perc_lines)):
                        file2.write(thirty_perc_lines[j]+'\n')
        temp_list = []
        temp_list.append(i)

文件1.csv

first file

文件2.csv

second file

Note: If there are only 3 lines, this code will add all the 3 lines in file1 and adds nothing to file2. You need to edit this code if you wish to change this behaviour.

相关问题 更多 >

    热门问题