当我插入数据库时,我希望相同的“标题”同时出现。
我使用Python作为一种编程语言,并使用Microsoft SQL Server作为数据库。
下面我举一个例子。
这就是我所拥有的:
A B C A B C A B C
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
这就是我想要的:
A B C
1 2 3
1 2 3
1 2 3
4 5 6
4 5 6
4 5 6
7 8 9
7 8 9
7 8 9
这是我使用的代码:
cursor = get_sql_conn().cursor()
localFile = 'C:\\Users\\dersimw\\Source\Repos\\nordpoolAnalyse\\data\\2011-3.xlsx'
excelFile = pd.ExcelFile(localFile)
sheetsList = []
rowsID = []
for allTheSheets in range(1,32):
convertingToChar = '%02d' % allTheSheets
sheetsList.append(str(convertingToChar))
for sheets in sheetsList:
df = excelFile.parse(sheets, skiprows=35)
df.dropna(axis=1, how='all', inplace = True)
df.fillna(0, inplace = True)
selectedColumns = df.iloc[: , [0,1,2,3,4]]
transposeColumns = selectedColumns.transpose()
print(transposeColumns)
for key, rows in transposeColumns.items():
# print("## Column: ", key, "\n")
columnInsertSql = "INSERT INTO DataSetValues (BuyAmount, BuyAggregated, BuyPrice, SellAmount, SellAggregated, SellPrice) VALUES("
columnCounter = 1
columnHasData = False
for key, column in rows.items():
if isinstance(column, int) or isinstance(column, float):
columnHasData = True
columnInsertSql += str(column)
if columnCounter != len(list(rows.items())):
columnInsertSql += ", "
columnCounter += 1
columnInsertSql += ")"
if columnHasData == True:
cursor.execute(columnInsertSql)
print("## SQL: " + columnInsertSql)
cursor.commit()
答案 0 :(得分:0)
这可能不是理想的解决方案,但可以按预期工作:
import pandas as pd
import numpy as np
# create dummy dataframe reppresting what you get from your SQL:
head = ['A','B','C']*3
rows = [[i for i in range(1,10)] for i in range(0,3)]
# put it in a pandas dataframe
df = pd.DataFrame(rows, columns=head)
my_dic = {}
for name, group in df.transpose().groupby(level=0):
my_dic[name] = group.values.reshape(np.size(group.values))
new_df = pd.DataFrame(my_dic)
输出:
new_df
Out[1]:
A B C
0 1 2 3
1 1 2 3
2 1 2 3
3 4 5 6
4 4 5 6
5 4 5 6
6 7 8 9
7 7 8 9
8 7 8 9