“Pandas删除最后一行”的版本间的差异

来自YTYZX有图有真相的百科
跳转至: 导航搜索
(创建页面,内容为“import pandas as pd import numpy as np df = pd.DataFrame({ 'Quantity': { 0: 50, 1: 50, 2: 70, 3: 50, 4: 80, 5: 10...”)
 
 
第1行: 第1行:
import pandas as pd
+
Pandas可以使用3种方法删除DataFrame的最后1行。
import numpy as np
+
1.使用iloc,具体语法为:df = df.iloc[:-1 , :]
df = pd.DataFrame({
+
 
    'Quantity': {
+
[[File:PandasDelLast1.png]]
        0: 50,
 
        1: 50,
 
        2: 70,
 
        3: 50,
 
        4: 80,
 
        5: 100,
 
        6: 30,
 
        7: 106
 
    },
 
    'Product_Names': {
 
        0: 'Mosuse',
 
        1: 'Keyboard',
 
        2: 'Headphones',
 
        3: 'CPU',
 
        4: 'Flash Drives',
 
        5: 'Tablets',
 
        6: 'Android Box',
 
        7: 'LCD'
 
    },
 
    'Product_Prices': {
 
        0: 100,
 
        1: 70,
 
        2: 150,
 
        3: 1500,
 
        4: 70,
 
        5: 1700,
 
        6: 2500,
 
        7: 1600
 
    },
 
})
 
  
 +
2.使用drop,具体语法为:df.drop(index=df.index[-1],axis=0,inplace=True)
 +
 
 +
[[File:PandasDelLast2.png]]
  
df.drop([len(df)-1],inplace=True)  #请勿使用df.drop([-1],inplace=True)
+
3.使用head,具体语法为:df = df.head(df.shape[0] -1)
print("df",df)
+
 
 +
[[File:PandasDelLast3.png]]

2022年8月28日 (日) 12:11的最新版本

Pandas可以使用3种方法删除DataFrame的最后1行。
1.使用iloc,具体语法为:df = df.iloc[:-1 , :]
  

PandasDelLast1.png

2.使用drop,具体语法为:df.drop(index=df.index[-1],axis=0,inplace=True)
  

PandasDelLast2.png

3.使用head,具体语法为:df = df.head(df.shape[0] -1)

PandasDelLast3.png