尝试将 5009 行从 csv 文件传输到 xlsx

Trying to transfer 5009 rows from csv file to xlsx

import pandas as pd    

df1=pd.read_csv('out.csv')
df2=pd.read_excel('file.xls')

df2['Location']=df1['Location']
df2['Sublocation']=df1['Sublocation']
df2['Zone']=df1['Zone']
df2['Subnet Type']=df1['Subnet Type']
df2['Description']=df1['Description']

newfile = input("Enter a name for the combined xlsx file: ")
print('Saving to new xlsx file...')
writer = pd.ExcelWriter(newfile)
df2.to_excel(writer, index=False)
writer.save()

基本上,它读取一个包含 5 列的 csv 文件,并读取一个包含现有列的 xls 文件,然后生成一个 xlsx 文件,其中两个文件与 5 个新列合并。

所以它有效,但仅适用于 4999 行,最后 10 行没有新 xlsx 文件中的 5 个新列。

我认为你应该附加数据

import pandas as pd    

df1=pd.read_csv('out.csv')
df2=pd.read_excel('file.xls')

df2.append(df1)

newfile = input("Enter a name for the combined xlsx file: ")
print('Saving to new xlsx file...')
writer = pd.ExcelWriter(newfile)
df2.to_excel(writer, index=False)
writer.save()

我对这个问题有点困惑,所以我想出了两个选项 1. 将 df1 附加到 df2 2. Merge df1 to df2(向现有df添加新列) .我认为在你的情况下,你在 csv 和 excel 中的行数不同,因此最后 10 行在输出中没有价值

import numpy as np
import pandas as pd

df1 = pd.DataFrame(np.array([
    ['a', 51, 61],
    ['b', 52, 62],
    ['c', 53, 63]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 31, 41],
    ['b', 32, 42],
    ['c', 33, 43],
    ['d',34,44]]),
    columns=['name', 'attr21', 'attr22'])

df3= df1.append(df2)
print df3
print pd.merge(df1,df2,on='name',how='right') 

很可能有一种方法可以在 pandas 中完成您想要的操作,但如果没有,您可以使用较低级别的包来完成您的任务。

要读取 CSV 文件,请使用 Python 附带的 csv 模块。以下代码将所有数据加载到 Python 列表中,其中列表的每个元素都是 CSV 中的一行。请注意,此代码并不像有经验的 Python 程序员编写的那样紧凑。我试图在 Python 初学者可读性和 "idiomatic":

之间取得平衡
import csv

with open('input1.csv', 'rb') as f:
    reader = csv.reader(f)
    csvdata = []
    for row in reader:
        csvdata.append(row)

要读取 .xls 文件,请使用 xlrd,它应该已经安装,因为 pandas 使用它,但如果需要,您可以单独安装它。同样,以下代码可能不是最短的,但希望易于理解:

import xlrd

wb = xlrd.open_workbook('input2.xls')
ws = wb.sheet_by_index(0)  # use the first sheet
xlsdata = []
for rx in range(ws.nrows):
    xlsdata.append(ws.row_values(rx))

最后,使用 XlsxWriter 将组合数据写入 .xlsx 文件。如果您使用 pandas 编写 Excel 文件,则可能已经安装了另一个软件包,但如果需要可以单独安装。再一次,我试图坚持使用相对简单的语言特性。例如,我避免了 zip(),它的工作原理对于 Python 初学者来说可能并不明显:

import xlsxwriter

wb = xlsxwriter.Workbook('output.xlsx')
ws = wb.add_worksheet()
assert len(csvdata) == len(xlsdata)  # we expect the same number of rows
for rx in range(len(csvdata)):
    ws.write_row(rx, 0, xlsdata[rx])
    ws.write_row(rx, len(xlsdata[rx]), csvdata[rx])
wb.close()

请注意,write_row() 允许您选择最左侧数据元素的目标单元格。所以我对每一行使用了两次:一次是在最左边写入 .xls 数据,另一次是用合适的偏移量写入 CSV 数据。