无法使用 .loc[] 直接以稀疏格式插入令人沮丧。恐怕我只有解决方法。
自从最初发布问题(和版本 0.25)以来,pandas 已弃用 SparseDataFrame。相反,它创建了一种数据类型 (SparseDtype),可以应用于 DataFrame 中的各个系列。换句话说,它不再是“全有或全无”。你可以:
- 将 DataFrame 中的几列转换为密集格式,同时保持其他列稀疏,
- 在密集列中使用 .loc[] 插入数据,
- 然后将这些列转换回稀疏列。
这显然 比将整个 DataFrame 转换为密集的内存占用少得多。
这是一个非常简单的函数来说明我的意思:
def sp_loc(df, index, columns, val):
""" Insert data in a DataFrame with SparseDtype format
Only applicable for pandas version > 0.25
Args
----
df : DataFrame with series formatted with pd.SparseDtype
index: str, or list, or slice object
Same as one would use as first argument of .loc[]
columns: str, list, or slice
Same one would normally use as second argument of .loc[]
val: insert values
Returns
-------
df: DataFrame
Modified DataFrame
"""
# Save the original sparse format for reuse later
spdtypes = df.dtypes[columns]
# Convert concerned Series to dense format
df[columns] = df[columns].sparse.to_dense()
# Do a normal insertion with .loc[]
df.loc[index, columns] = val
# Back to the original sparse format
df[columns] = df[columns].astype(spdtypes)
return df
简单使用示例:
# DÉFINITION DATAFRAME SPARSE
df1 = pd.DataFrame(index=['a', 'b', 'c'], columns=['I', 'J'])
df1.loc['a', 'J'] = 0.42
df1 = df1.astype(pd.SparseDtype(float))
# | I | J
# ----+-----+--------
# a | nan | 0.42
# b | nan | nan
# c | nan | nan
df1.dtypes
#I Sparse[float64, nan]
#J Sparse[float64, nan]
df1.sparse.density
# 0.16666666666666666
# INSERTION
df1 = sp_loc(df1, ['a','b'], 'I', [-1, 1])
# | I | J
# ----+-----+--------
# a | -1 | 0.42
# b | 1 | nan
# c | nan | nan
df1.sparse.density()
# 0.5