search
HomeBackend DevelopmentPython TutorialIntroduction to simple operation methods of pandas.DataFrame (create, index, add and delete) in python

This article introduces the simple operation methods of pandas.DataFrame (creation, indexing, addition and deletion) in python, including related information on creation, indexing, addition and deletion, etc. The introduction in the article is very detailed. Friends who need it can For reference, let’s take a look below.

Preface

Recently, I have searched a lot of operation instructions on the Internet for pandas.DataFrame, all of which are basic. operations, but the combination of these operations still takes time to correctly operate the DataFrame, and it took me a long time to adjust the bug. I will make some summaries here for the convenience of you, me and others. Friends who are interested, please come and take a look.

1. Simple operation to create DataFrame:

1. Create according to dictionary:

In [1]: import pandas as pd
In [3]: aa={'one':[1,2,3],'two':[2,3,4],'three':[3,4,5]}
In [4]: bb=pd.DataFrame(aa)
In [5]: bb
Out[5]: 
 one three two
0 1 3 2
1 2 4 3
2 3 5 4`

The keys in the dictionary are the columns in the DataFrame, but there is no index value, so you need to set it yourself. If not set, the default is to start counting from zero.

bb=pd.DataFrame(aa,index=['first','second','third'])
bb
Out[7]: 
 one three two
first 1 3 2
second 2 4 3
third 3 5 4

2. Create from a multi-dimensional array

import numpy as np
In [9]: del aa
In [10]: aa=np.array([[1,2,3],[4,5,6],[7,8,9]])
In [11]: aa
Out[11]: 
array([[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]])
In [12]: bb=pd.DataFrame(aa)
In [13]: bb
Out[13]: 
 0 1 2
0 1 2 3
1 4 5 6
2 7 8 9

To create from a multi-dimensional array, you need to assign columns and index to the DataFrame, otherwise it will be the default, which is ugly.

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])
In [15]: bb
Out[15]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

3. Create with other DataFrame

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])
bb
Out[15]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9
cc=bb[['one','three']].copy()
Cc
Out[17]: 
 one three
22 1 3
33 4 6
44 7 9

The copy here is a deep copy. Changing the value in cc cannot change the value in bb.

cc['three'][22]=5
bb
Out[19]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

cc
Out[20]: 
 one three
22 1 5
33 4 6
44 7 9

2. Index operation of DataFrame:

For a DataFrame, indexing is the most troublesome and error-prone.

1. Indexing one or more columns is relatively simple:

bb['one']
Out[21]: 
22 1
33 4
44 7
Name: one, dtype: int32

For multiple column names, the input column names need to be stored in a list to be a collerable variable. , otherwise an error will be reported.

bb[['one','three']]
Out[29]: 
 one three
22 1 3
33 4 6
44 7 9

2. Index one record or several records:

bb[1:3]
Out[27]: 
 one two three
33 4 5 6
44 7 8 9
bb[:1]
Out[28]: 
 one two three
22 1 2 3

Note here that the colon is required, otherwise it will be an index column. .

3. Index certain records of variables in certain columns. This tortured me for a long time:

First type

bb.loc[[22,33]][['one','three']]
Out[30]: 
 one three
22 1 3
33 4 6

You cannot change the value here. You can only read the value but not write it. It may be related to the loc() function:

bb.loc[[22,33]][['one','three']]=[[2,2],[3,6]]
In [32]: bb
Out[32]: 
 one two three
22 1 2 3
33 4 5 6
44 7 8 9

The second type: also only You can see

bb[['one','three']][:2]
Out[33]: 
 one three
22 1 3
33 4 6

If you want to change the value, an error will be reported.

In [34]: bb[['one','three']][:2]=[[2,2],[2,2]]
-c:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
F:\Anaconda\lib\site-packages\pandas\core\frame.py:1999: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
 return self._setitem_slice(indexer, value)

The third type: you can change the value of the data! ! !

Iloc is indexed according to the number of rows and columns of data, not counting index and columns

bb.iloc[2:3,2:3]
Out[36]: 
 three
44 9

bb.iloc[1:3,1:3]
Out[37]: 
 two three
33 5 6
44 8 9
bb.iloc[0,0]
Out[38]: 1

The following is the proof:

bb.iloc[0:4,0:2]=[[9,9],[9,9],[9,9]]
In [45]: bb
Out[45]: 
 one two three
22 9 9 3
33 9 9 6
44 9 9 9

3. In the original Create a new column or several columns on the DataFrame

1. Use nothing. You can only create one column separately. Multiple columns are not easy to use. Personal test is invalid:

bb['new']=[2,3,4]
bb
Out[51]: 
 one two three new
22 9 9 3 2
33 9 9 6 3
44 9 9 9 4
bb[['new','new2']]=[[2,3,4],[5,3,7]]
KeyError: "['new' 'new2'] not in index"

The list assigned is basically assigned in the order of the given index value, but generally we need to assign the corresponding index. If you want more advanced assignments, look at the following.

2. Use a dictionary to assign values ​​to multiple columns by index:

aa={33:[234,44,55],44:[657,77,77],22:[33,55,457]}
In [58]: bb=bb.join(pd.DataFrame(aa.values(),columns=['hi','hello','ok'],index=aa.keys()))
In [59]: bb
Out[59]: 
 one two three new hi hello ok
22 9 9 3 2 33 55 457
33 9 9 6 3 234 44 55
44 9 9 9 4 657 77 77

Here aa is a nested dictionary and list, which is equivalent to a record. Use keys as index name instead of the usual default column names. The purpose of matching multiple columns by index is achieved. Since the storage of dict() is chaotic, using dict() without assigning its index value will cause confusion in the records. This is worth noting.

4. Delete multiple columns or records:

Delete columns

bb.drop(['new','hi'],axis=1)
Out[60]: 
 one two three hello ok
22 9 9 3 55 457
33 9 9 6 44 55
44 9 9 9 77 77

Delete record

bb.drop([22,33],axis=0)
Out[61]: 
 one two three new hi hello ok
44 9 9 9 4 657 77 77

Share with you an article about summing rows and columns and adding new rows and columns in pandas.DataFrame in python. Friends who are interested can take a look.

There are many functions of DataFrame that have not been covered yet. They will be covered in the future. After reading the API on the official website, I will continue to share it. Everything is ok.

Related articles:

About pandas.DataFrame in python to sum rows and columns and add new rows and columns sample code

Detailed explanation of the sample code of pandas.DataFrame method of excluding specific rows in python

The above is the detailed content of Introduction to simple operation methods of pandas.DataFrame (create, index, add and delete) in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),