pandas

pandas,第1张

文章目录
  • pandas_dataframe元素类型转换并集 *** 作/差集 *** 作//bool&str混合数据类型排序问题
  • TypeError: unsupported operand type(s) for +: 'bool' and 'str'
    • datafram数据类型转化
      • astypes函数
      • map(applymap)+python cast
    • 并集&差集&索引重建重排序
        • reset_index参考
      • 相关集合论原理

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函数
  • pandas.DataFrame.astype — pandas 1.4.2 documentation (pydata.org)

  • 这个方案感觉不是很通用(复杂情况下的实践)

map(applymap)+python cast
  • pandas.DataFrame.applymap

这个方案比较靠谱

# 将所有元素类型通过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参考
  • pandas.DataFrame.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)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/942279.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-18
下一篇2022-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存