简体   繁体   English

使用python(熊猫)删除excel中的第一行和第一列

[英]Deleting first row and column in excel using python (pandas)

I'm trying to delete the first row and the first column in excel files using pandas.我正在尝试使用 pandas 删除 excel 文件中的第一行和第一列。 On the left it can be seen what i have and on the right what i want:在左边可以看到我拥有的东西,在右边可以看到我想要的东西:

excel擅长
擅长

I have been using pandas to transpose the values (this works) and after that to delete the first row and column.我一直在使用熊猫来转置值(这有效),然后删除第一行和第一列。 The code is as follows:代码如下:

import pandas as pd

file_name = 'ex1.xlsx'

sheets = pd.read_excel(file_name, sheet_name=None)  
sheet_name, df = next(iter(sheets.items()))         
df = df.T                                        
df = df.drop(0, axis = 1)                           
df = df.drop(0, axis = 0)                           
df.to_excel(file_name, sheet_name)  

The first drop does not give back an error, but does not do anything in the excel file (it does not delete the first column. The second drop gives back an error [0] not found in axis .第一次放置不会返回错误,但不会在 excel 文件中执行任何操作(它不会删除第一列。第二次放置会返回错误[0] not found in axis

What am i doing wrong?我究竟做错了什么? Why do i get this error and why does the first drop do nothing?为什么我会收到这个错误,为什么第一滴什么都不做?

If first row are columns names and first column are index values use:如果第一行是列名,第一列是索引值,则使用:

sheets = pd.read_excel(file_name, sheet_name=None)  
sheet_name, df = next(iter(sheets.items())) 

Test index and columns:测试索引和列:

print (df.columns)
print(df.index)

df = df.T                                        
                       
df.to_excel(file_name, sheet_name, index=False, header=False)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM