Python - Pandas 删除 excel 中的特定行/列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47498667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Pandas delete specific rows/columns in excel
提问by onlyf
i have the following excel file, and i would like to clean specific rows/columns so that i can further process the file.
我有以下 excel 文件,我想清理特定的行/列,以便我可以进一步处理该文件。
I have tried this, but i have not managed to remove any of the blank lines, i ve only managed to trim from those containing data. Here, i was trying to only save the data from the third row and on.
我试过这个,但我没有设法删除任何空行,我只设法从那些包含数据的行中删除。在这里,我试图只保存第三行及以后的数据。
xl = pd.ExcelFile("MRD.xlsx")
df = xl.parse("Sheet3")
df2 = df.iloc[3:]
writer4 = pd.ExcelWriter('pandas3.out.no3lines.xlsx', engine='xlsxwriter')
table5 = pd.DataFrame(df2)
table5.to_excel(writer4, sheet_name='Sheet1')
writer4.save()
I specifically want to remove rows 1, 3 (the empty ones) and the first column, so that i can pivot it. Is there a way to do this? Thank you.
我特别想删除第 1、3 行(空行)和第一列,以便我可以旋转它。有没有办法做到这一点?谢谢你。
回答by furas
You can use drop(...)
to remove rows, and drop(..., axis=1)
to remove columns
您可以使用drop(...)
删除行和drop(..., axis=1)
删除列
data = [
['', '', '', ''],
['', 1, 2, 3],
['', '', '', ''],
['', 7, 8, 9],
]
import pandas as pd
df = pd.DataFrame(data)
# drop first column - [0]
df = df.drop(0, axis=1)
# drop first and third row - [0,2]
df = df.drop([0,2])
print(df)
Before:
前:
0 1 2 3
0
1 1 2 3
2
3 7 8 9
After:
后:
1 2 3
1 1 2 3
3 7 8 9