Skip to content

Instantly share code, notes, and snippets.

@canwe
Created April 19, 2018 09:48
Show Gist options
  • Save canwe/1f651e07171f7b61ff98bf6e7c4dad0c to your computer and use it in GitHub Desktop.
Save canwe/1f651e07171f7b61ff98bf6e7c4dad0c to your computer and use it in GitHub Desktop.
Take a look at the DataFrames changes.
Suppose there is a DataFrame here,
>>> aDF
name pay
0 Mayue 3000
1 Lilin 4500
2 Wuyun 8000

add columns
Add a tax column into aDF.
>>> aDF['tax'] = [0.05, 0.05, 0.1]
>>> aDF
name pay tax
0 Mayue 3000 0.05
1 Lilin 4500 0.05
2 Wuyun 8000 0.1

2. add rows
We can use loc or iloc to do data selection operation by label or integer index. The append() method and concat() function are also ok.
If we want to add a new row into aDF,
>>> aDF.loc[5] = {'name': 'Liuxi', 'pay': 5000, 'tax': 0.05}
>>> aDF
name pay tax
0 Mayue 3000 0.05
1 Lilin 4500 0.05
2 Wuyun 8000 0.1
5 Liuxi 5000 0.05

3. delete data
The del operation can actually delete the data. The drop() method is safer than the del operation because it can return a new object instead of changing the original DataFrames.
Drop the row which label is 5,
>>> aDF.drop(5)
name pay tax
0 Mayue 3000 0.05
1 Lilin 4500 0.05
2 Wuyun 8000 0.1

Drop the tax column,
>>> aDF.drop('tax', axis = 1)
name pay
0 Mayue 3000
1 Lilin 4500
2 Wuyun 8000
5 Liuxi 5000
>>> aDF
name pay tax
0 Mayue 3000 0.05
1 Lilin 4500 0.05
2 Wuyun 8000 0.1
5 Liuxi 5000 0.05

4. modify
modify the column,
>>> aDF['tax'] = 0.03
>>> aDF
name pay tax
0 Mayue 3000 0.03
1 Lilin 4500 0.03
2 Wuyun 8000 0.03
5 Liuxi 5000 0.03

modify the row,
>>> aDF.loc[5] = ['Liuxi', 9800, 0.05]
name pay tax
0 Mayue 3000 0.03
1 Lilin 4500 0.03
2 Wuyun 8000 0.03
5 Liuxi 9800 0.05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment