我在excel文件中有一个大约27列的小型数据框。我实际上对编码很陌生,需要帮助将一个数据帧分成各种excel文件,基于数据帧的列号。我尝试了一个小代码,它给了我同样的错误:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
data = pd.read_excel('/Users/jorge/Desktop/Data/Book1.xlsx')
counts, bins, patches = plt.hist(data.values, bins=range(0,
int(max(data.values)+5), 5))
df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
df.columns= np.arange(0, len(data.columns))
for i in range (0, 27):
name = '/Users/user/Desktop/Data/t40-%d.xlsx' % (i+1)
print (name)
print (header[i])
writer = pd.ExcelWriter(name)
df.to_excel(writer,'Sheet2',columns=header[i])
writer.save()
为数据框的列命名并尝试将EACH列导出为单独的文件,但我不断收到错误:
AttributeError: 'Series' object has no attribute 'columns'
有什么我做错了,我怎么能这样做之后,它使用适当的bin将直方图输出到基于列数的不同excel文件,所以会有27个excel文件27列。非常感谢任何帮助,谢谢。
答案 0 :(得分:0)
试试这个
import pandas as pd
from pandas import ExcelWriter
data = pd.read_excel('/Users/jorge/Desktop/Data/Book1.xlsx',header=None)
for i in data.columns:
name = '/Users/user/Desktop/Data/t40-'+str(i+1)+'.xlsx'
writer = pd.ExcelWriter(name)
pd.DataFrame(data[i]).to_excel(writer,'Sheet1')
writer.save()
答案 1 :(得分:0)
用这个改变循环
for i in range (0, 27):
name = '/Users/user/Desktop/Data/t40-%d.xlsx' % (i+1)
writer = pd.ExcelWriter(name)
df2 = pd.DataFrame(df[i])
df2.to_excel(writer,'Sheet2',index = False, header = False)
writer.save()