我有一個資料框。此資料框包含三個單元格id、horstid、date。單元格date只有一個NaN值。我想要下面的代碼適用于熊貓,我想要它與 numpy.
首先,我想將資料框轉換為 numpy 陣列。我想以后是要找到所有行date是NaN和列印。之后我想洗掉所有這些行。但是我怎么能在 numpy 中做到這一點呢?
這是我的資料框
id horstid date
0 1 11 2008-09-24
1 2 22 NaN
2 3 33 2008-09-18
3 4 33 2008-10-24
這是我的代碼。這適用于罰款,但適用于熊貓。
d = {'id': [1, 2, 3, 4], 'horstid': [11, 22, 33, 33], 'date': ['2008-09-24', np.nan, '2008-09-18', '2008-10-24']}
df = pd.DataFrame(data=d)
df['date'].isna()
[OUT]
0 False
1 True
2 False
3 False
df.drop(df.index[df['date'].isna() == True])
[OUT]
id horstid date
0 1 11 2008-09-24
2 3 33 2008-09-18
3 4 33 2008-10-24
我想要的是上面沒有pandas但有numpy的代碼。
npArray = df.to_numpy()
date = npArray [:,2].astype(np.datetime64)
[OUT]
ValueError: Cannot create a NumPy datetime other than NaT with generic units
uj5u.com熱心網友回復:
這是一個基于Numpy和純python的解決方案:
df = pd.DataFrame.from_dict(dict(horstid = [11, 22, 33, 33], id=[1,2,3,4], data=['2008-09-24', np.nan, '2008-09-18', '2008-10-24']))
a = df.values
index = list(map(lambda x: type(x) != type(1.),a[:, 2]))
print(a[index,:])
[[11 1 '2008-09-24']
[33 3 '2008-09-18']
[33 4 '2008-10-24']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338371.html
