search
HomeBackend DevelopmentPython TutorialPandas read and modify excel operation strategy in Python (code example)

The content of this article is about the Pandas read and modify excel operation guide (code example) in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Environment: python 3.6.8

Let’s take a certain Miser number as an example:

Pandas read and modify excel operation strategy in Python (code example)

Pandas read and modify excel operation strategy in Python (code example)

>>> pd.read_excel('1.xlsx', sheet_name='Sheet2')
     名字   等级 属性1   属性2  天赋
0  四九幻曦  100  自然  None  21
1  圣甲狂战  100  战斗  None   0
2  时空界皇  100   光    次元  27

We use the pd.read_excel() function here to read excel. Let’s take a look at the API of read_excel(). Here we only intercept Some commonly used parameters:

pd.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None)
io: Obviously, it is the path name string of the excel file

(if there is Chinese, it is python2 Laotie needs to use decode() to decode into unicode string)
For example:

>>> pd.read_excel('例子'.decode('utf-8))
sheet_name: Return the specified sheet
If sheet_name is specified as None, the entire sheet will be returned
If multiple sheets need to be returned, sheet_name## can be returned #Specify as a list, for example ['sheet1', 'sheet2']You can specify the selected

sheet based on the name string or index of sheet

>>> # 如:
>>> pd.read_excel('1.xlsx', sheet_name=0)
>>> pd.read_excel('1.xlsx', sheet_name='Sheet1')
>>> # 返回的是相同的 DataFrame
header: Specify the header of the data table, the default value is 0, that is, the first row will be used as the header
usecols: Read the specified column, you can also use the name or index value
>>> # 如:
>>> pd.read_excel('1.xlsx', sheet_name=1, usecols=['等级', '属性1'])
>>> pd.read_excel('1.xlsx', sheet_name=1, usecols=[1,2])
>>> # 返回的是相同的 DataFrame
Until one day Tiger reaches a level, you can change it like this. Of course, you can use

.iloc or .loc objects

>>> # 读取文件
>>> data = pd.read_excel("1.xlsx", sheet_name="Sheet1")

>>> # 找到 等级 这一列,再在这一列中进行比较
>>> data['等级'][data['名字'] == '泰格尔'] += 1
>>> print(data)
LOOK! He's upgraded! !

>>> data
     名字   等级 属性1   属性2  天赋
0  艾欧里娅  100  自然     冰  29
1   泰格尔   81   电    战斗  16
2  布鲁克克  100   水  None  28
Now we save it

data.to_excel('1.xlsx', sheet_name='Sheet1', index=False, header=True)
index: The default is
True, whether to add row index, just go to the picture above!
Pandas read and modify excel operation strategy in Python (code example)
Left is
False, right is True
header: Default is
True, whether Add a column mark and picture it!
The left one is Pandas read and modify excel operation strategy in Python (code example)False, the right one is True
and
io, sheet_name parameter usage is the same as function pd. read_excel()
What if we capture a few more animals or add a few more attributes? Reference is given here:

New column data:
data['column name'] = [value 1, value 2, ...]
>>> data['特性'] = ['瞬杀', 'None', '炎火']
>>> data
     名字   等级 属性1   属性2  天赋    特性
0  艾欧里娅  100  自然     冰  29    瞬杀
1   泰格尔   80   电    战斗  16  None
2  布鲁克克  100   水  None  28    炎火
New Row data, the num of the row here is the id value automatically added to the row in excel

data.loc[num of the row] = [value 1, value 2, ...], (note the difference with
.iloc difference)

>>> data.loc[3] = ['小火猴', 1, '火', 'None', 31, 'None']
>>> data
     名字   等级 属性1   属性2  天赋    特性
0  艾欧里娅  100  自然     冰  29    瞬杀
1   泰格尔   80   电    战斗  16  None
2  布鲁克克  100   水  None  28    炎火
3   小火猴    1   火  None  31  None
After adding a row or a column, how to delete a row or a column? You can use

.drop()function

>>> # 删除列, 需要指定axis为1,当删除行时,axis为0
>>> data = data.drop('属性1', axis=1) # 删除`属性1`列
>>> data
     名字   等级   属性2  天赋    特性
0  艾欧里娅  100     冰  29    瞬杀
1   泰格尔   80    战斗  16  None
2  布鲁克克  100  None  28    炎火
3   小火猴    1  None  31  None

>>> # 删除第3,4行,这里下表以0开始,并且标题行不算在类, axis用法同上
>>> data = data.drop([2, 3], axis=0)
>>> data
     名字   等级 属性2  天赋    特性
0  艾欧里娅  100   冰  29    瞬杀
1   泰格尔   80  战斗  16  None

>>> # 保存
>>> data.to_excel('2.xlsx', sheet_name='Sheet1', index=False, header=True)

The above is the detailed content of Pandas read and modify excel operation strategy in Python (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!