pandas_dataframe元素类型转换并集操作/差集操作/bool&str混合数据类型排序问题/TypeError:unsupported operand type(s)

pandas_dataframe元素类型转换并集操作/差集操作//bool&str混合数据类型排序问题

TypeError: unsupported operand type(s) for +: ‘bool’ and ‘str’

  • 排序中,可能遇到类似的报错,我们可以尝试通过数据类型转换来解决

datafram数据类型转化

某些时候,我们的数据中包含了一些特殊值,其类型容易被pandas识别为其他(譬如从str被识别为bool类型)

  • 错误类型
    • TypeError : unsupported operand type(s) for +: 'bool' and 'str'

astypes函数

map(applymap)+python cast

这个方案比较靠谱

# 将所有元素类型通过python元素类型强制转化,转换为str类型
df3=df3.applymap(lambda x:str(x))
# 这个时候再执行列上的元素排序不会出现数据类型不同的问题!
df3.sort_values(by='spelling')

并集&差集&索引重建重排序

  • 以下代码时候再jupyter方式运行查看
  • dataframe可以自己构造的对象

核心函数:

  • concat()

  • drop_duplicate()

# 并集(去重)(得到原生不重复的全集)
set_union_df=pd.concat([old_df,new_df]).drop_duplicates()
set_union_df
# 根据数据列重新产生(重新建立索引并排序:reset_index(drop=True));
# 或者不用drop参数,直接截取指定列(旧有的索引列自然会被去掉!)
# set_union_df=set_union_df.reset_index()[['spelling']]
# 差集(基于全集的去重操作;求取独有的那部分元素)
##
# 注意concat(的参数)&drop_duplicates(的参数keep)
set_diff_df=pd.concat([set_union_df,old_df]).drop_duplicates(keep=False)
set_diff_df=set_diff_df.reset_index()[['spelling']]
set_diff_df
reset_index参考

相关集合论原理

# try diff compare(optional):以下是差集和pandas方法的推演
s1=pd.Series([2,3,4,5])
s1
df1=pd.DataFrame(s1)
s2=pd.Series([1,3,4,5])
df2=pd.DataFrame(s2)
set_union_df = pd.concat([df2, df1]).drop_duplicates()
set_union_df
#集合论中: A-B=A-AB
# 我们可以利用concat(A+B,B).drop_duplicates(keep=False)得到类似效果
# df2-df1
set_diff_df=pd.concat([set_union_df,df1]).drop_duplicates(keep=False)
set_diff_df
#df1-df2
set_diff_df=pd.concat([set_union_df,df2]).drop_duplicates(keep=False)
set_diff_df
print(set_union_df)
posted @   xuchaoxin1375  阅读(12)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-05-16 windows远程桌面mstsc@保存登录凭证问题CredentialGuard@中转投屏等细节@局域网环境
2021-05-16 图论算法的基本概念/松弛操作/最短路径估计
点击右上角即可分享
微信分享提示