是否可以创建一个稀疏的Pandas DataFrame,其中的列都包含浮点数和字符串? 即,我有一个数据框:
df2 = pd.DataFrame({'A':[0., 1., 2., 0.],
'B': ['a','b','c','d']}, columns=['A','B'])
我想将其转换为稀疏数据帧,但df2.to_sparse(fill_value = 0。)给出:
ValueError: could not convert string to float: d
有没有办法让这项工作?
答案 0 :(得分:1)
你可以做的是将你的字符串映射到ints / floats并将你的列B映射到他们的dict查找值到一个新的列C然后创建稀疏的数据帧,如下所示:
temp={}
# we want just the unique values here for the dict
for x in enumerate(df2['B'].unique().tolist()):
val, key = x
temp[key]=val
temp
Out[106]:
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
# now add this column
In [108]:
df2['C']=df2['B'].map(temp)
df2
Out[108]:
A B C
0 0 a 0
1 1 b 1
2 2 c 2
3 0 d 3
# now pass the two columns to create the sparse matrix:
In [109]:
df2[['A', 'C',]].to_sparse(fill_value=0)
Out[109]:
A C
0 0 0
1 1 1
2 2 2
3 0 3