Python 从数据透视表中删除空值和切片
我在切割数据透视框时遇到问题,因此无法获得高于某个阈值的结果。我试图过滤掉低于最小值的结果。我的数据框看起来是这样的:Python 从数据透视表中删除空值和切片,python,pandas,dataframe,pivot,slice,Python,Pandas,Dataframe,Pivot,Slice,我在切割数据透视框时遇到问题,因此无法获得高于某个阈值的结果。我试图过滤掉低于最小值的结果。我的数据框看起来是这样的: Qty Index Store_Nbr 201712 201801 201802 201803 201804 201805 20180
Qty
Index Store_Nbr 201712 201801 201802 201803 201804 201805 201806 201807 201808
0 1 356 275 293 256 313 421 493 291 385
1 2 147 316 343 416 361 483 438 136 461
2 3 266 370 162 346 451 414 296 478 295
3 4 322 179 353 241 370 247 423 391 194
4 5 249 389 480 450 102 482 137 251 153
... ... ... ... ... ... ... ... ... ... ...
30 30 0 0 0 0 0 0 0 0 0
31 31 0 0 0 0 0 0 0 0 0
32 32 0 0 0 0 0 0 0 0 0
33 33 392 311 151 488 135 239 212 104 122
34 34 0 0 0 0 0 0 0 0 -1
在使用godzilla=godzilla[godzilla['Qty']>150]
之后,我得到了下面的数据帧,其中它已将所有零转换为空,并且没有过滤掉任何内容
Qty
Index Store_Nbr 201712 201801 201802 201803 201804 201805 201806 201807 201808
0 NaN NaN 275 293 256 313 421 493 291 385
1 NaN 147 316 343 416 361 483 438 136 461
2 NaN 266 370 162 346 451 414 296 478 295
3 NaN NaN 179 353 241 370 247 423 391 194
4 NaN 389 480 450 102 482 137 251 153 153
... ... ... ... ... ... ... ... ... ... ...
30 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
31 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
32 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
33 NaN NaN 311 151 488 135 239 212 104 122
34 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
我试过做godzilla.dropna(axis=0,inplace=True,how='any')
,它返回一个空的数据帧和godzilla=godzilla.dropna(subset=godzilla['Qty'])
它返回一个键错误:“Qty”。我感到困惑的是,它将零转换为空,以及为什么切片不工作。在尝试对数据透视进行过滤/切片时,有什么妙语吗
请注意**我在数据框中有多个数量被旋转。首先,将小于150的每个值替换为无。
然后,应筛选出至少有1个None值的行,如中所述 这应该可以做到:
# replaces every value of the DataFrame lower than 150 with None
godzilla = pd.DataFrame([
[x if not isinstance(x, (int, float)) or x >= 150 else None for x in j
] for j in godzilla.as_matrix()])
# replaces every value of the Column "Qty" lower than 150 with None
df["Qty"] = [x if not isinstance(x, (int, float)) or x >= 20 else None for x in df["Qty"]
#dropna will drop all rows with at least 1 null value
df = df.dropna(how='any',axis=0)
对!!您使用的是分层结构,即多索引。这就是为什么不删除列,而是替换为
NaN
。如果除了数量
之外没有其他索引,您可以使用:
godzilla.columns = godzilla.columns.droplevel()
然后使用dropna()
:
我终于明白了。抱歉耽搁了。感谢你们提出的答案。这个错误完全是我的错。在前面的代码中,我使用了
.drop_index()
,因为当时我没有意识到我可以使用.index
操作索引。更正代码后,使用godzilla=godzilla[godzilla['Qty']>150].dropna()设置参数时没有问题 如果一行的所有列都不是空的,你想怎么办?如果一行甚至有一个空值,我想将其排除在外。我认为一个包括“数量”以外的其他内容的完整数据透视的想法会很有帮助-事实上,尝试制作一个虚拟数据帧并对其应用解决方案,通常会发现问题。这是行不通的。如果我能让切片首先工作,那将是最优的。取回这个“TypeError:“method”对象是不可编辑的“你到底做了什么?我得到了一个没有值的空数据帧。”@Celius,对分层数据帧进行切片的正确方法是什么,这样我就可以从一开始就过滤掉0?它们作为元组工作,所以你的索引是('Qty','Store_Nbr'),('Qty','201712'),('Qty','201801'),等等…这是有意义的,因为Store_Nbr
中的所有行都是空的,也就是说,它们不满足条件。您应该考虑在使用<代码> DROPNA之前删除它(如何=‘任意’,轴=0’)< /代码>
godzilla = godzilla.dropna(how='any',axis=0)