我有一個這樣的系列
s = pd.Series([[1,2,3],[1,2,3],np.nan,[1,2,3],[1,2,3],np.nan])
我只是想讓.NaN替換為[0,0,0].
我試過了
s.fillna([0,0,0]) # TypeError: "value" parameter must be a scalar or dict, but you passed a "list"
s[s.isna()] = [[0,0,0],[0,0,0]] # just replaces the NaN with a single "0". WHY?!
s.fillna("NAN").replace({"NAN":[0,0,0]}) # ValueError: NumPy boolean array indexing assignment cannot
#assign 3 input values to the 2 output values where the mask is true
s.fillna("NAN").replace({"NAN":[[0,0,0],[0,0,0]]}) # TypeError: NumPy boolean array indexing assignment
# requires a 0 or 1-dimensional input, input has 2 dimensions
我真的不明白,為什么前兩種方法不起作用(也許我得到第一種,但第二種我無法理解)。
感謝這個SO-question and answer,我們可以通過
is_na = s.isna()
s.loc[is_na] = s.loc[is_na].apply(lambda x: [0,0,0])
但由于apply通常很慢我無法理解,為什么我們不能使用replace或上面的切片
uj5u.com熱心網友回復:
Pandas 痛苦地使用串列,這里是 hacky 解決方案:
s = s.fillna(pd.Series([[0,0,0]] * len(s), index=s.index))
print (s)
0 [1, 2, 3]
1 [1, 2, 3]
2 [0, 0, 0]
3 [1, 2, 3]
4 [1, 2, 3]
5 [0, 0, 0]
dtype: object
uj5u.com熱心網友回復:
Series.reindex
s.dropna().reindex(s.index, fill_value=[0, 0, 0])
0 [1, 2, 3]
1 [1, 2, 3]
2 [0, 0, 0]
3 [1, 2, 3]
4 [1, 2, 3]
5 [0, 0, 0]
dtype: object
uj5u.com熱心網友回復:
檔案表明該值不能是list.
用于填充孔的值(例如 0),或者是值的 dict/Series/DataFrame,指定用于每個索引(對于 Series)或列(對于 DataFrame)的值。不在 dict/Series/DataFrame 中的值將不會被填充。此值不能是串列。
這可能是當前實作的一個限制,并且缺少修補源代碼,您必須求助于變通方法。
但是,如果您不打算使用鋸齒狀陣列,那么您真正想要做的可能是替換pd.Series()為pd.DataFrame(),例如:
s = pd.DataFrame(
[[1, 2, 3],
[1, 2, 3],
[np.nan],
[1, 2, 3],
[1, 2, 3],
[np.nan]],
dtype=pd.Int64Dtype()) # to mix integers with NaNs
s.fillna(0)
# 0 1 2
# 0 1 2 3
# 1 1 2 3
# 2 0 0 0
# 3 1 2 3
# 4 1 2 3
# 5 0 0 0
如果您確實需要使用鋸齒狀陣列,則可以使用任何建議的解決方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475604.html
上一篇:Azure管道無法使用embedAndSignAppleFrameworkForXcode和fastlane構建Kotlin多平臺共享框架
