下面的代码有什么区别?

时间:2019-12-22 08:56:44

标签: python pandas

这两行代码有什么区别?

print(df.drop(df.where(df['Quantity']==0).index).rename(columns={'Weight':'Weight(oz)'}))  

print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'}))

换句话说,

有什么区别
df.where(df['Quantity']==0).index

具有以下输出

enter image description here

df[df['Quantity'] == 0].index

具有以下输出

enter image description here

1 个答案:

答案 0 :(得分:3)

有所不同,因为它使用DataFrame.where

df.where(df['Quantity']==0).index

它仅将不匹配的行替换为NaN,因此结果的索引与原始df相同。


但是,如果您使用:

df[df['Quantity'] == 0].index 

它称为boolean indexing,并按条件过滤DataFrame,因此索引值与原始df不同。

示例

df = pd.DataFrame({'Quantity':[0,1,2,1,1,0],
                   'Weight':  [4,5,6,7,7,8]},
                    index=list('abcdef'))
print (df)
   Quantity  Weight
a         0       4
b         1       5
c         2       6
d         1       7
e         1       7
f         0       8

#removed all index values - empty DataFrame
print(df.drop(df.where(df['Quantity']==0).index).rename(columns={'Weight':'Weight(oz)'}))  
Empty DataFrame
Columns: [Quantity, Weight(oz)]
Index: []

print (df.where(df['Quantity']==0).index)
Index(['a', 'b', 'c', 'd', 'e', 'f'], dtype='object')

print (df.where(df['Quantity']==0))
   Quantity  Weight
a       0.0     4.0
b       NaN     NaN
c       NaN     NaN
d       NaN     NaN
e       NaN     NaN
f       0.0     8.0

#removed rows with 0 in Quantity
print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'}))
   Quantity  Weight (oz.)
b         1             5
c         2             6
d         1             7
e         1             7

print (df[df['Quantity'] == 0].index)
Index(['a', 'f'], dtype='object')

print (df[df['Quantity'] == 0])
   Quantity  Weight
a         0       4
f         0       8

在我看来,使用drop的解决方案过于复杂,使用逆逻辑更为简单-在0列中选择所有不包含Quantity的行:

print(df[df['Quantity'] != 0].rename(columns={'Weight': 'Weight (oz.)'}))
   Quantity  Weight (oz.)
b         1             5
c         2             6
d         1             7
e         1             7