加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 可以用字符串列创建稀疏的Pandas DataFrame吗?

发布时间:2020-12-20 13:38:01 所属栏目:Python 来源:网络整理
导读:是否可以创建一个稀疏的Pandas DataFrame,其中的列都包含浮点数和字符串? 即,我有一个数据帧: df2 = pd.DataFrame({'A':[0.,1.,2.,0.],'B': ['a','b','c','d']},columns=['A','B']) 我想将其转换为稀疏数据帧,但df2.to_sparse(fill_value = 0.)给出: Valu
是否可以创建一个稀疏的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

有没有办法让这项工作?

解决方法

你可以做的是将你的字符串映射到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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读