从数据框熊猫派生的系列中删除一个值?

时间:2021-01-15 14:25:19

标签: python pandas

我刚刚在下面看到了这段代码,我想知道为什么没有从数据框中删除该值。

import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)
df.Brand.drop(axis=0,index = 0,inplace=True)
print (df)

有人能解释一下这里发生了什么吗? PS:- 我知道如何删除 drop() 值,但想知道为什么什么都没有改变。

1 个答案:

答案 0 :(得分:0)

0 列的索引 Brand 处的值正在下降。看看这个:

In [1240]: df.Brand.drop(axis=0,index = 0,inplace=True)
In [1242]: df.Brand
Out[1242]: 
1    Toyota Corolla
2        Ford Focus
3           Audi A4
Name: Brand, dtype: object

但我同意你的看法,当你 print(df) 时,它表现为什么也没发生:

In [1243]: df
Out[1243]: 
            Brand  Price
0     Honda Civic  22000
1  Toyota Corolla  25000
2      Ford Focus  27000
3         Audi A4  35000

好像是个错误。

如果您改为这样做:

In [1246]: df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

In [1247]: df
Out[1247]: 
            Brand  Price
0     Honda Civic  22000
1  Toyota Corolla  25000
2      Ford Focus  27000
3         Audi A4  35000

In [1248]: df.Brand = df.Brand.drop(axis=0,index = 0)

In [1249]: df
Out[1249]: 
            Brand  Price
0             NaN  22000
1  Toyota Corolla  25000
2      Ford Focus  27000
3         Audi A4  35000

结果符合预期。