簡體   English   中英

使用指定數量的python組合2個csv文件

[英]Combine 2 csv file using python with the specified amount

我想要合並2個文件CSV數據,但不是所有數據。 例如:a.csv + b.csv,其中b.csv有20個數據。 但我想從中獲取10個數據,然后獲取11-20個數據。 或者前10和后10

然后將前10個數據插入a.csv,將第二個10個數據插入a.csv我的問題是如何才能只獲取特定的總數據?

這是我的代碼:

import pandas as pd

df1 = pd.read_csv('testNegatif.csv')
df2 = pd.read_csv('trainNegatif.csv', nrows=10)

output=df1.append(df2)
output.to_csv("output.csv", sep=',')

我希望結果返回我想要的,但實際結果是組合所有數據。

不使用熊貓。 閱讀每個文件的行; 從一個文件的數據添加十行到另一個; 將結果寫入另一個文件。

with open('a.csv') as f:
    data = f.readlines()
with open('b.csv') as f:
    bdata = f.readlines()

data.extend(bdata[:10])

with open('output.csv', 'w'):
    f.writelines(data)

如果文件是巨大的並且您不想將整個內容讀入內存,請使用一些itertools函數。

import itertools
with open('a.csv') as a, open('b.csv') as b, open('output.csv', 'w') as out:
    first_ten = itertools.islice(b, 10)
    for line in itertools.chain(a, first_ten):
        out.write(line)

假設兩個文件具有相同的列數。

import pandas as pd
import numpy as np
# Creating two dataframes with data that overlap, so we don't want all of the 'b' data.
# We want to strip off '3,4,5' as they exist in 'a' as well
# ----------Creating the data frames----------
a = [1,2,3,4,5]
b = [3,4,5,6,7,8,9,10]

dfa = pd.DataFrame(a)
dfa.to_csv('one.csv', index=False)

dfb = pd.DataFrame(b)
dfb.to_csv('two.csv', index = False)
# ---------------------------------------------

# --------Reading through the dataframes-------
one = pd.read_csv('one.csv')
two = pd.read_csv('two.csv')
# ---------------------------------------------

# Stripping off the first 3 data of 'two' the list
output = one.append(two[3:])
output.to_csv("output.csv", sep=',', index=False)
# ---------------------------------------------

我希望這回答了你的問題。 對你來說重要的部分是output = one.append(two[3:]) 有更復雜的方法來做同樣的事情,但這是最簡單的。

正如我的評論中提到的,你可以使用nrows

import pandas as pd

df1 = pd.read_csv('testNegatif.csv')
df2 = pd.read_csv('trainNegatif.csv', nrows=10)

output=df1.append(df2)
output.to_csv("output.csv", sep=',')

請參閱: https//pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html了解更多選項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM