Python 是否可以使用字符串列创建稀疏数据帧?

Python 是否可以使用字符串列创建稀疏数据帧?,python,pandas,Python,Pandas,是否可以创建一个既包含浮点数又包含字符串的列的稀疏数据帧? 即,我有一个数据帧: df2 = pd.DataFrame({'A':[0., 1., 2., 0.], 'B': ['a','b','c','d']}, columns=['A','B']) 我想将其转换为稀疏数据帧,但df2.to_sparse(fill_value=0)给出: 有什么方法可以使这项工作正常吗?您可以将字符串映射到int/float,并将列B映射到它们的dict查找值到新的

是否可以创建一个既包含浮点数又包含字符串的列的稀疏数据帧? 即,我有一个数据帧:

df2 = pd.DataFrame({'A':[0., 1., 2., 0.], 
                    'B': ['a','b','c','d']}, columns=['A','B'])
我想将其转换为稀疏数据帧,但df2.to_sparse(fill_value=0)给出:


有什么方法可以使这项工作正常吗?

您可以将字符串映射到int/float,并将列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
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