[英]Making a pandas dataFrame based on some column values of another dataFrame
我有一個熊貓DataFrame df1,具有以下內容:
Serial N year current
B 10 14
B 10 16
B 11 10
B 11
B 11 15
C 12 11
C 9
C 12 13
C 12
我想制作一個基於df1
的DataFrame,但該數據幀的任何包含空值的行都被刪除。 例如:
Serial N year current
B 10 14
B 10 16
B 11 10
B 11 15
C 12 11
C 12 13
我嘗試過這樣的事情
df1=df[~np.isnan(df["year"]) or ~np.isnan(df["current"])]
但是我收到以下錯誤:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
可能是什么問題呢?
您可以致電dropna
來實現此目的:
df1 = df.dropna()
至於為什么嘗試失敗or
運算符不理解在比較類似數組的結構時的原因,因為如果1個或多個元素滿足布爾條件則模棱兩可,則應使用按位運算符&
, |
和~
代表and
, or
而not
代表。 另外,對於多個條件,由於運算符的優先級,您需要將條件包裝在括號中。
In [4]:
df.dropna()
Out[4]:
Serial N year current
0 B 10 14
1 B 10 16
2 B 11 10
4 B 11 15
5 C 12 11
7 C 12 13
如果您確實有空單元格而不是NaN:
In [122]: df
Out[122]:
Serial_N year current
0 B 10.0 14.0
1 B 10.0 16.0
2 B 11.0 10.0
3 B 11.0
4 B 11.0 15.0
5 C 12.0 11.0
6 C 9.0
7 C 12.0 13.0
8 C 12.0
In [123]: a.replace('', np.nan).dropna()
Out[123]:
Serial_N year current
0 B 10.0 14.0
1 B 10.0 16.0
2 B 11.0 10.0
4 B 11.0 15.0
5 C 12.0 11.0
7 C 12.0 13.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.