How does pandas read dataframe specific rows and columns
This article mainly introduces how pandas reads the specific ranks of dataframe, the article introduces in great detail, has a certain reference value, interested friends must read it!
1. Fetch by column, by index / row, by specific row
Import numpy as npfrom pandas import DataFrameimport pandas as pd df=DataFrame (np.arange (12). Reshape ((3Jing 4)), index= ['one','two','thr'], columns=list (' abcd')) df ['a'] # take a column df [['a']] # take column a, column b # ix can be indexed numerically You can also use index and column index df.ix [0] # take line 0 df.ix [0:1] # take line 0 df.ix ['one':'two'] # take line one, line two df.ix [0df.ix 2d0] # take line 0,1, column 0 df.ix [01df.ix] # take line 0, a column df.ix [01df.ix] # take line 0,1 Abc column df.ix ['one':'two','a':'c'] # take one and two rows, abc column df.ix [0one 2Magazine 1] # take rows 0,1, 0th column df.ix [0one 2j0one':'two','a':'c' 2] # take rows 0,1, 0th and 1st column # loc can only be fetched through index and columns, not numeric df.loc [' one','a'] # one line A column df.loc ['one':'two','a'] # one to two row, a column df.loc [' one':'two','a':'c'] # one to two row, a to c column df.loc ['one':'two', [' axiomagery]] # one to two row, ac column # iloc can only be indexed numerically You cannot use the index name df.iloc [0:2] # the first 2 rows df.iloc [0] # Line 0 df.iloc [0df.iloc 2 Magazine 2] # 0, 1 line, 0 column df.iloc [[0 Percoll 2], [1 Personality 2]] # # rows 0, 2, 1, 2, 3 columns # iat take a single value, you can only numerically index df.iat [1Mague 1] # Line 1 1 column # at takes a single value, only index and columns indexes df.at ['one','a'] # one row, a column
two。 Take the line according to the condition
Select row records equal to certain values with = = df.loc [df ['column_name'] = = some_value] to select whether a column is a certain type of value or not with isindf.loc [' column_name'] .isin (some_values)] selection of multiple conditions & df.loc [(df ['column'] = = some_value) & df [' other_column'] .isin (some_values)] to select rows that are not equal to certain values! = df.loc [df ['column_name']! = some_value] isin returns a series of values. If you want to select values that do not meet this condition, use ~ df.loc [~ df [' column_name'] .isin (some_values)]
3. Replace after picking it up
Df = pd.DataFrame ({"id": [25 id: [25 id: [25 daisy','tony','peter','tommy','ana','david','ken','jim' 53 15], "sex": list ('mfmfmfmf'),' score': [1.2,2.3,3.4,4.5), "name": ['daisy','tony','peter','tommy','ana','david','ken','jim']})
Replace male (m) with 1 and female (f) with 0
Method 1:
Df.ix [df ['sex'] = =' frenzy Magazine sex'] = 0df.ix [df ['sex'] =' Maureen pageant'] = 1
Note: in the above code, the 'sex' after the comma acts as a fixed column name
Method 2:
Df.sex [df ['sex'] = =' m'] = 1df.sex [df ['sex'] = =' f'] = 0
4. Delete a specific line
# to delete the column "score"