一個按條件過濾pandas中行的函數,對于非空的dataframe可以正常工作,但是對于帶列名的空的dataframe,過濾后的空datafram缺丟失了列名
問題復現如下:
In [5]: t1 = pd.DataFrame(columns=['a','b'])
In [6]: t2=pd.DataFrame({'a':[-1,1],'b':[2,3]})
In [7]: t1
Out[7]:
Empty DataFrame
Columns: [a, b]
Index: []
In [8]: t2
Out[8]:
a b
0 -1 2
1 1 3
In [13]: def myfunc1(row):
...: if row.empty:
...: print(row)
...: return True
...: if int(row['a'])>0:
...: return True
...: else:
...: return False
...:
In [17]: t2[t2.apply(myfunc1, axis=1)]
Out[17]:
a b
1 1 3
In [18]: t1[t1.apply(myfunc1, axis=1)]
Series([], dtype: float64)
Out[18]:
Empty DataFrame
Columns: []
Index: []
t2結果過濾得到row['a']>0的新dataframe,但是t1經過過濾為什么丟失了columns呢?因為后續處理要用到columns,所以我想知道
為什么丟失了columns
2 回答

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
因為t1,t2內部的篩選條件不一樣.
t2內部條件其實是取第二行。
In [18]: t2.apply(myfunc, axis=1)
Out[18]:
0 False
1 True
dtype: bool
In [19]: t2[t2.apply(myfunc, axis=1)]
Out[19]:
a b
1 1 3
t1的內部條件則不同,沒有True,False,是一個空的DataFrame
In [20]: t1.apply(myfunc, axis=1)
Out[20]: Series([], dtype: float64)
In [21]: t1[t1.apply(myfunc, axis=1)]
Series([], dtype: float64)
添加回答
舉報
0/150
提交
取消