我使用SQLAlchemy從MSSQL數據庫中查詢數據,然後保存爲帶有熊貓的excel文件。我正在尋找類似於T-SQL的RTRIM的東西,以便從我的數據中刪除任何尾隨的空白。刪除SQLAlchemy或Pandas中的空格
我知道如何從列標題中刪除空格,但不能從數據本身中刪除。所以我要麼在查詢時或者在熊貓數據框中刪除空白字符,但對於如何解析(因爲大多數搜索在解析時如何刪除空白區域,而不是寫入數據)我沒有任何想法。
到目前爲止我的代碼是:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session,sessionmaker
from sqlalchemy import (Column, Integer, String, Boolean, ForeignKey, DateTime, Sequence, Float)
from sqlalchemy import create_engine
import pandas as pd
import openpyxl
pd.core.format.header_style = None
pd.core.format.number_format = None
def data_frame(query, columns):
def make_row(x):
return dict([(c, getattr(x, c)) for c in columns])
return pd.DataFrame([make_row(x) for x in query])
engine = create_engine('mssql+pyodbc://u:[email protected]/MYDBt?driver=SQL Server', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Tranv(Base):
__tablename__ = "Transactions"
part_number = Column(String(20), primary_key=True)
time_stamp = Column(String(20))
employee_number = Column(String(6))
action = Column(String(20))
newvarv = session.query(Tranv).filter_by(employee_number='001841').filter_by(time_stamp='2015-10-01 10:49:53.230')
dfx = data_frame(newvarv, [c.name for c in Tranv.__table__.columns])
dfx.columns = dfx.columns.str.strip()
dfx = dfx.rename(columns=lambda x: x.strip())
writer = pd.ExcelWriter('C:\\Users\\grice\\Desktop\\Auto_Scrap_Report\\testy.xlsx')
writer.date_format = None
writer.datetime_format = None
dfx.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
要刪除的列中的所有條目結尾的空白做' df [