如何使用熊猫在python中编写Excel行

时间:2019-01-28 11:06:09

标签: python excel pandas dataframe row

我正在从excel文件中读取一行,并尝试将其写回excel,但它写为列,我正在使用熊猫

import pandas as pd 
import xlsxwriter as xlsw

cols = [1, 2, 3, 4, 5, 6, 7]
df = pd.read_excel('test.xlsx', sheet_names='Sheet1', usecols=cols)
df.head()
dfr = df.iloc[6]
dfr = pd.DataFrame(dfr,columns=['Voltage', 'Amps', 'Expected 
Voltage','Expected Current', 'ExpectedLogicalValue', 'Actual Voltage'])

writer = pd.ExcelWriter('Output.xlsx', engine='xlsxwriter')
dfr.to_excel(writer, sheet_name="data", index=False)
writer.save()

1 个答案:

答案 0 :(得分:3)

我认为您需要对一行DataFrame进行两次list选择,然后设置新的列名称:

dfr = df.iloc[[6]]
dfr.columns= = ['Voltage', 'Amps', 'Expected Voltage','Expected Current', 
                'ExpectedLogicalValue', 'Actual Voltage', 'Another col']

另一种解决方案:

cols = [1, 2, 3, 4, 5, 6, 7]
names = ['Voltage', 'Amps', 'Expected Voltage','Expected Current', 
         'ExpectedLogicalValue', 'Actual Voltage', 'Another col']

df = pd.read_excel('test.xlsx', sheet_names='Sheet1', usecols=cols, names=names, skiprows=1)

dfr = df.iloc[[6]]