【问题标题】:Auto-Adjust the Width of Excel Columns with Pandas使用 Pandas 自动调整 Excel 列的宽度
【发布时间】:2022-10-05 14:42:11
【问题描述】:

我正在尝试我的列将根据数据自动调整,但它们会给我一个错误是否有可能我的数据适合在 excel 文件中他们向我显示此错误ValueError: Shape of passed values is (1, 12), indices imply (1, 1) 有没有办法解决这些错误请检查它是否有任何可见的解决方案

索引暗示 (1, 1)` 有什么办法可以解决这些错误请检查一下

import enum
import requests
from bs4 import BeautifulSoup
import json
import pandas as pd 
import numpy as np
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3"
}
r = requests.get("https://www.fleetpride.com/parts/otr-coiled-air-hose-otr6818")
soup = BeautifulSoup(r.content, "html5lib")
raw_json = ""
for table_index,table in enumerate( soup.find_all("script")):
    if('CCRZ.detailData.jsonProductData = {"' in str(table)):
        x=str(table).split('CCRZ.detailData.jsonProductData = {"')
        raw_json = "{\""+str(x[-1]).split('};')[0]+"}"
        break
      
      
req_json = json.loads(raw_json)
# with open("text_json.json","w")as file:
#     x=json.dump(req_json,file,indent=4)

temp = req_json
cat=temp['product']['prodBean']['friendlyUrl'][:11]
catu=temp['product']['prodBean']['friendlyUrl'][11:55]
catk=temp['product']['prodBean']['friendlyUrl'][56:71]
cup=temp['product']['prodBean']['friendlyUrl'][72:]
title=temp['product']['prodBean']['name']
specification=temp['product']['prodBean']['sku']
spec1=temp['product']['prodBean']['productSpecsS'][15]['specValue']
spec2=temp['product']['prodBean']['productSpecsS'][30]['specValue']
spec3=temp['product']['prodBean']['productSpecsS'][28]['specValue']
spec4=temp['product']['prodBean']['productSpecsS'][29]['specValue']
spec5=temp['product']['prodBean']['productSpecsS'][27]['specValue']
spec6=temp['product']['prodBean']['productSpecsS'][18]['specValue']
spec7=temp['product']['prodBean']['productSpecsS'][19]['specValue']
spec8=temp['product']['prodBean']['productSpecsS'][20]['specValue']

fea=spec6+spec7+spec8

spec11=temp['product']['prodBean']['ECrossReferencesS'][0]['Interchange_Part_Number__c']
spec12=temp['product']['prodBean']['ECrossReferencesS'][1]['Interchange_Part_Number__c']
spec13=temp['product']['prodBean']['ECrossReferencesS'][2]['Interchange_Part_Number__c']
spec14=temp['product']['prodBean']['ECrossReferencesS'][3]['Interchange_Part_Number__c']
spec15=temp['product']['prodBean']['ECrossReferencesS'][4]['Interchange_Part_Number__c']
spec16=temp['product']['prodBean']['ECrossReferencesS'][5]['Interchange_Part_Number__c']

cross=spec11+spec12+spec13+spec14+spec15+spec16

wev=[]
web={
    'category':cat,
    'sub_category':catu,
    'sub_category1':catk,
    'sub_category2':cup,
    'name':title,
    'Model_No':specification,
    'VMRS':spec1,
    'width_each':spec2,
    'Quantity':spec3,
    'Height_each':spec4,
    'cross_reference':cross,
    'feature':fea
    
}
# print(web)

wev.append(web)
df = pd.DataFrame(np.random.randint(0,100,size=(1, 12)),columns=wev)
# print(df)
df.to_csv('second.csv', index=False, encoding='utf-8')

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    好吧,下面的代码应该可以工作:

    writer = pd.ExcelWriter('test_file.xlsx') 
    df.to_excel(writer, sheet_name='test_sheet', index=False, na_rep='NaN')
    
    for column in df:
        column_width = max(df[column].astype(str).map(len).max(), len(column))
        col_idx = df.columns.get_loc(column)
        writer.sheets['test_sheet'].set_column(col_idx, col_idx, column_width)
    
    writer.save()
    

    【讨论】:

      【解决方案2】:

      此代码在使用时有效'openpyxl'作为您的引擎,有时pip install xlsxwriter 无法解决问题。下面的代码就像一个魅力。根据需要编辑任何部分。

      def text_length(text):
          """
          Get the effective text length in characters, taking into account newlines
          """
          if not text:
              return 0
          lines = text.split("
      ")
          return max(len(line) for line in lines)
      
      def _to_str_for_length(v, decimals=3):
          """
          Like str() but rounds decimals to predefined length
          """
          if isinstance(v, float):
              # Round to [decimal] places
              return str(Decimal(v).quantize(Decimal('1.' + '0' * decimals)).normalize())
          else:
              return str(v)
      
      
      def auto_adjust_xlsx_column_width(df, writer, sheet_name, margin=3, length_factor=1.0, decimals=3, index=False):
      
          sheet = writer.sheets[sheet_name]
          _to_str = functools.partial(_to_str_for_length, decimals=decimals)
          # Compute & set column width for each column
          for column_name in df.columns:
              # Convert the value of the columns to string and select the 
              column_length =  max(df[column_name].apply(_to_str).map(text_length).max(), text_length(column_name)) + 5
              # Get index of column in XLSX
              # Column index is +1 if we also export the index column
              col_idx = df.columns.get_loc(column_name)
              if index:
                  col_idx += 1
              # Set width of column to (column_length + margin)
              sheet.column_dimensions[openpyxl.utils.cell.get_column_letter(col_idx + 1)].width = column_length * length_factor + margin
          # Compute column width of index column (if enabled)
          if index: # If the index column is being exported
              index_length =  max(df.index.map(_to_str).map(text_length).max(), text_length(df.index.name))
              sheet.column_dimensions["A"].width = index_length * length_factor + margin
      

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 1970-01-01
        • 2018-02-02
        • 2021-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        相关资源
        最近更新 更多