1) Specify row index and column index labels

index Properties can be specified DataFrame Index array in structure ,  columns Property to specify the row containing the column name ,

While using name attribute , Through the analysis of a DataFrame The example goes on df Set up ( df.index.name and df.columns.name) You can for DataFrame Structure specifies row index labels and column index labels .

    for example , Specify row index label and column index label for product price list , The sample code is as follows :

In [24]: df.index.name = 'id'
In [25]: df.columns.name = 'item
In [26]: df
Out[26]:
item product price
id
0 The TV 2300.0
1 Air conditioner 1980.0
2 Washing machine 780.0
3 The computer NaN

2) Add a list of elements

by DataFrame Instance to add a list of elements is to specify DataFrame The name of the new column of the instance , And assign a value to it . for example , Add a discount rate column to the product price , The sample code is as follows :

In [27]: df['discount']=[0.9,0.85,0.95,1]
In [28]: df
Out[28]:
item product price discount
id
0 The TV 2300.0 0.90
1 Air conditioner 1980.0 0.85
2 Washing machine 780.0 0.95
3 The computer NaN 1.00

Or use insert() Function to add a list of elements at the specified location . for example , After the discount rate column , Add a list of prices (“price”) Multiply by the discount rate (“discount”) The actual price of (“Actual_price”) Column , The sample code is as follows :

In [29]: df.insert(3,'Actual_price',df['price']*df['discount'])
In [30]: df
Out[30]:
item product price discount Actual_price
id
0 The TV 2300.0 0.90 2070.0
1 Air conditioner 1980.0 0.85 1683.0
2 Washing machine 780.0 0.95 741.0
3 The computer NaN 1.00 NaN

3) Add a line of elements

by DataFrame The way to add a row of elements to an instance is to use loc The attribute is DataFrame Add a new line to the instance , And assign a value to this line . for example , Add the price line of a mobile phone product to the product price , The sample code is as follows :

In [31]: df.loc['add_row'] = [' mobile phone ',1900,1,1900]
In [32]: df
Out[32]:
item product price discount Actual_price
id
0 The TV 2300.0 0.90 2070.0
1 Air conditioner 1980.0 0.85 1683.0
2 Washing machine 780.0 0.95 741.0
3 The computer NaN 1.00 NaN
add_row mobile phone 1900.0 1.00 1900.0

4) Modify a line of elements

modify DataFrame A row of elements in an object , Just use loc Attribute specifies DataFrame The row index in the instance , And assign a value to this line . for example , Modify the data of the computer line in the product price , The sample code is as follows :

In [33]: df.loc[3] = [' The computer ',4500,1,4500]
In [34]: df
Out[34]:
item product price iscount Actual_price
id
0 The TV 2300.0 0.90 2070.0
1 Air conditioner 1980.0 0.85 1683.0
2 Washing machine 780.0 0.95 741.0
3 The computer 4500.0 1.00 4500.0
add_row mobile phone 1900.0 1.00 1900.0

5) Modify a list of elements or an element

modify DataFrame A list of elements in an instance , Just specify DataFrame The column name in the instance , Store a list of elements to be updated in the array , Then assign the array to this column .
for example , Change the price in the product price to the new price [3000,2300,560,5600], The sample code is as follows :

In [35]: df['price']=[3000,2300,560,5600,1880]
In [36]: df
Out[36]:
item product price discount Actual_price
id
0 The TV 3000 0.90 2070.0
1 Air conditioner 2300 0.85 1683.0
2 Washing machine 560 0.95 741.0
3 The computer 5600 1.00 4500.0
add_row mobile phone 1880 1.00 1900.0

Modify an element , Just select the element , Just give it a value . for example df['discount'][1]=0.96.

6) Remove elements

6.1) Use del Command to delete a list of elements

If you want to delete all the data in an entire column , Use del command . for example , Delete the actual price column in the product price , The sample code is as follows :

In [37]: del df['Actual_price']
In [38]: df
Out[38]:
item product price discou
id
0 The TV 3000 0.90
1 Air conditioner 2300 0.85
2 Washing machine 560 0.95
3 The computer 5600 1.00
add_row mobile phone 1880 1.00

6.2) Use pop() Function to delete a list of elements

pop() Function to delete the selected column from the original data block , The column is no longer retained in the original block . for example , Use pop() Function to delete the discount rate column , The sample code is as follows :

In [39]: df.pop('discount')
Out[39]: id
0 0.90
1 0.85
2 0.95 3 1.00
add_row 1.00
Name: discount, dtype: float64

6.3) Use drop() Function to delete a column of elements or a row of elements

stay drop() There are two parameters in the function , One parameter is axis, When parameters axis=1 when , Then delete the column elements ; When axis=0 when , Then delete the line element . Another parameter is inplace, When inplace by True when ,drop() Function to perform internal deletion , No value returned , The original data has changed ; When inplace by False when , The original data will not change , Just output new variables, delete .

for example , To add 1 Column discount rate column , And then use drop() Function to set parameters axis=1 and inplace=True Delete column element of discount rate , The sample code is as follows :

In [40]: df['discount']=0.94
In [41]: df.drop(['discount'],axis=1,inplace=True)

If you want to delete a line , Is set axis=0, And specify the row index or row label to delete . for example , Delete row label as add_row A line of elements , The sample code is as follows :

In [42]: df.drop(['add_row'],axis=0,inplace=True)

If you want to delete multiple lines , In addition to setting the axis=0 Outside , Also specify the row index or row label to delete , for example , Delete the first 1 Xing He 3 Row element , The sample code is as follows :

In [43]: df.drop([0,2],axis=0,inplace=True)

7) Filter elements

about DataFrame object , You can also filter elements by specifying criteria . for example , The price of the product is higher than 2000 Meta product information , The sample code is as follows :

In [44]: df[df['price']>2000]
Out[44]:
item product price
id
0 The TV 3000
1 Air conditioner 2300
3 The computer 5600

for example , All the elements in the product price are less than 2000 Meta product information , The sample code is as follows :

In [45]: df[df<2000]
Out[45]:
item product price
id
0 The TV NaN
1 Air conditioner NaN
2 Washing machine 560
3 The computer NaN

Back to DataFrame Object contains only numbers that satisfy the condition , The position of each element remains unchanged , Other elements that do not meet the criteria are replaced with NaN.

8) Determine whether an element exists

Use isin() Function to determine whether a given list of elements is contained in DataFrame In structure , If the given element is contained in the data structure ,isin() The function returns True, Otherwise, the return is False. Use this function to filter DataFrame Data in column .

For example, to determine whether there is “ The computer ” and 2300 These two elements , And return the element that satisfies the condition , The sample code is as follows :

In [46]: df[df.isin([' The computer ',2300])]
Out[46]:
item product price
id
0 NaN NaN
1 NaN 2300.0
2 NaN NaN
3 The computer NaN

9) DataFrame Transposition

DataFrame The data structure is similar to the table data structure , When processing table data , Transpose operations are often used , Change column to row , Rows become columns .pandas Provides a simple transpose method , By calling T Attribute gets DataFrame Transpose form of object .

For example, transpose the product price data structure , The sample code is as follows :

In [47]: df.T
Out[47]:
id 0 1 2 3
item
product The TV Air conditioner Washing machine The computer
price 3000 2300 560 5600

pandas DataFrame The new ranks of , modify 、 Delete 、 Screening 、 Judging elements and transpose operations

  1. pandas DataFrame How to delete a row or column

    pandas DataFrame Summary of the series of articles on the addition, deletion, examination and modification of : pandas DaFrame The creation method of pandas DataFrame The query method of pandas DataFrame How to delete a row or column pand ...

  2. ext,exrReturn newly added , Modify, delete, etc

    package cn.edu.hbcf.common.vo; /** * Ext Ajax Returns the object * * @author * @date 2012-02-21 19:30:00 * */ publ ...

  3. pandas DataFrame How to modify

    pandas DataFrame Summary of the series of articles on the addition, deletion, examination and modification of : pandas DaFrame The creation method of pandas DataFrame The query method of pandas DataFrame How to delete a row or column pand ...

  4. pandas DataFrame The query method of (loc,iloc,at,iat,ix Usage and difference of )

    pandas DataFrame Summary of the series of articles on the addition, deletion, examination and modification of : pandas DaFrame The creation method of pandas DataFrame The query method of pandas DataFrame How to delete a row or column pand ...

  5. pandas DataFrame The creation method of

    pandas DataFrame Summary of the series of articles on the addition, deletion, examination and modification of : pandas DaFrame The creation method of pandas DataFrame The query method of pandas DataFrame How to delete a row or column pand ...

  6. Python How to delete pandas DataFrame Of / Several columns

    Delete pandas DataFrame Of / Several columns : Method 1 : direct del DF['column-name']   Method 2 : use drop Method , There are three equivalent expressions : 1. DF= DF.drop('co ...

  7. [PHP] - Laravel - list 、 newly added 、 modify 、 Delete example

    Preface Laravel The default is to bring it with you CURD The function of , Using routing Route::resource It can be done . But in real projects , This is often not what we need . Because a project will have more complex calculations . Verification and other functions . Here's a look at the project ...

  8. MYSQL Basics 01( newly added , modify , Delete )

    Let's start with , I have been using MSSQL, For work reasons , Hundreds of them every day sql sentence , And it lasted for a few years ; Due to the change of job, the main contact at present is MYSQL; So start learning MYSQL. My study plan is very simple , I am here MSSQL send ...

  9. About C# and ASP.NET Chinese vs App.config and Web.config In the file [appSettings] and [connectionStrings] Nodes are added 、 modify 、 Delete and read related operations

    Some of the projects I've done recently , Often need to use the configuration file operation of the application , Such as app.config and web.config Configuration file for , Especially for [appSettings] and [connectionStrings] ...

  10. 17、 Hand to hand Extjs5( seventeen ) New modules 、 modify 、 Delete operation

    In the last section Grid During the exhibition, we made a function that the amount unit can be selected manually , If you want to add other features , Just follow this pattern , For example, you want to change the color of the amount field . Decimal digit . Whether the zero value shows . Currency symbols . Units are shown in the title bar or in gold ...

Random recommendation

  1. AEAI ESB Training program

    1. summary The purpose of this document is to enable users to better operate . maintain . Serve the whole ESB system platform , The information system platform not only needs mature and stable products , More skilled operation and maintenance personnel are needed , In order to better carry out scientific and effective operation and maintenance work . AEA ...

  2. android Tips ( Two )

    One . How to control Android  LED etc. ?( Set up NotificationManager Some parameters of ) The code is as follows : final int ID_LED=19871103; NotificationManage ...

  3. Uncaught ReferenceError: console is not defined

    Today I write javascript The code encountered this amazing problem , It's a mistake to say that it's built-in console non-existent , And then I changed to alert Not good either. . As a rule, these are js Things built into the code shouldn't have this kind of error . But Baidu's discovery doesn't seem to have ...

  4. mysql Index classification

    In the database table , Indexing fields can greatly improve query speed . By making good use of these indexes , Can make MySQL More efficient query and operation . Indexes are the key to quick searches .MySQL The establishment of index for MySQL It is very important to run efficiently . Here are some common ...

  5. CreateFeatureClass abnormal , Trying to read or write to protected memory Access

    The following exception occurred when creating the feature , puzzled . After many tests , Just change the file name to something else . The name of the self generated file is " The first 3 strip ", Then change the file name to "A3" etc. , Can be created normally . Later ...

  6. [ turn ]jquery.vTicker( Scroll vertically )

    Transferred to :http://www.w3ci.com/plugin/660.html brief introduction vTicker It's a very small one jQuery Scroll plug in vertically , Only after compression 2KB.vTicker Support custom scrolling time ...

  7. js Implementation process of

    step 1.   Read in the first code block . step 2.   Do grammar analysis , If there is a mistake, report a grammatical error ( For example, the brackets don't match ), And jump to step5. step 3.   Yes var Variables and function Define to do " precompile ...

  8. The finger of the sword Offer—— A store of knowledge - Fault detection 、 Performance tuning and Java Class loading mechanism

    The finger of the sword Offer-- A store of knowledge - Fault detection . Performance tuning and Java Class loading mechanism Fault detection . performance tuning What tools can be used to detect memory leaks (1)MerroyAnalyzer: A feature rich java Heap dump file analysis tool , Sure ...

  9. vue.js Development SPA Common problems and solutions

    List access to the details page reference question . For example, from the product list page to the product details page , Need to pass a product id; <router-link :to="{path: 'detail', query: {id: 1}} ...

  10. ubuntu ifconfig Only lo No, ens33 The problem of

    If ifconfig It only shows lo, ifconfig -a But it's normal ens33. Then you can do the following : service network-manager stop rm /var/lib/Netwo ...