在Python中出现错误:列数必须与键的长度相同

2024-09-19 23:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫在excel中过滤数据文件.In第69行“我需要拆分总金额列以获取新列名”“Amount”“和”“Satang”“。旧Excel可以运行,但现在我正在将Excel文件更改为相同的格式。错误:”“列的长度必须与键相同”“。我在新Excel文件中将新列与旧Excel文件选中。你知道吗

这是我的密码:

    files = pd.read_excel('R:/ASMP/00_AP_AUTO_MAIL/'+month_folder+'/STAFF_CLAIM_IE_'+today+'_01.xlsx',heading = None, encoding = 'utf-8')#Path file
files_final = files.fillna(0)
files_final_header = files_final.iloc[5]
files_final.columns = files_final_header
files_final_x = files_final[6:]
files_final_xx = files_final_x['Voucher Number Status'] = files_final_x.rename(columns={'Voucher Number Status' : 'Voucher_Number_Status'})
files_final_xx['Voucher Number Status'] = files_final_xx['Voucher_Number_Status'].str.strip()
files_final = (files_final_xx[files_final_xx.Voucher_Number_Status.apply(lambda x: isinstance(x, str))])
files_final_xa = files_final

   ###Add new coulmns name = ref2
files_final_xa['ref_2'] = files_final_xa['Invoice Number'].apply(lambda x: x[3:])
files_final_xa['Amount'] = files_final_xa['Payment Amount Pay']
   ###Add new coulmns name = Amount, satang

**files_final_xa[['Amount','Satang']] = files_final_xa.Amount.apply( lambda x: pd.Series(str(x).split('.')))**
###Add new coulmns name = break for break loop
files_final_xa['break'] = '1'
files_final_xa['break1'] = '1'

Files = files_final_xa.filter(['Supplier Name','Payment Date','Voucher Number Status','ref_2','Amount','Satang','Voucher Number Status','Description'])
Files_final = Files[Files.Description.str.contains('Cash')].fillna(0)
count = Files_final['Supplier Name'].count()

#Export file(File in User path)
Files_final.to_excel('STAFF_CLAIM_IE_'+today+'_01_Filter.xlsx')

[This's my Excel File]

[This's my error.]


Tags: 文件numberstatusfilesexcelamountfinalapply
1条回答
网友
1楼 · 发布于 2024-09-19 23:32:21

你可以试试这个

(files_final_xa['Amount'], files_final_xa['Satang'] = 
     files_final_xa.Amount.astype(str).str.split('.', 1).str)

例如

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.2, 3.4]})
>>> df['b'], df['c'] = df['a'].astype(str).str.split('.', 1).str
>>> df
     a  b  c
0  1.2  1  2
1  3.4  3  4

但你要注意列的类型

>>> df.dtypes
a    float64
b     object
c     object
dtype: object

如果要floatinteger键入列,可以添加以下表达式

(files_final_xa[['Amount', 'Satang']] = 
    files_final_xa[['Amount', 'Satang']].astype(float))

或者对于integer

(files_final_xa[['Amount', 'Satang']] = 
    files_final_xa[['Amount', 'Satang']].astype(int))

相关问题 更多 >