【问题标题】:How do you simplify .str.contains code with multiple contains variables?如何简化具有多个包含变量的 .str.contains 代码?
【发布时间】:2019-07-24 03:57:58
【问题描述】:

我正在使用 Series.str.contains() 函数来查找字典中的值是否包含在特定列的字符串中。我的代码有效,但我正在尝试简化它。

我尝试使用 for 循环遍历列表中的值。我的尝试在下面。

 total_joined_list=[joined_groc_lst,joined_util_lst]

 for i in range(len(total_joined_list)):



groc_amount,util_amount=abs(round(df.loc[df['Description'].str.contains('\b'+i+'\b',na=False),'Amount'].sum(),2))

这是当前的工作代码。

 joined_groc_lst = '|'.join(expenses_dict['Groceries'])
 joined_util_lst = '|'.join(expenses_dict['Utilities'])



groc_amount=abs(round(df.loc[df['Description'].str.contains('\b'+joint_groc_lst+'\b',na=False),
                    'Amount'].sum(),2))
 util_amount=abs(round(df.loc[df['Description'].str.contains('\b'+joint_util_lst+'\b',na=False),
                    'Amount'].sum(),2))

我希望我的函数创建两个变量; groc_amount 和 util_amount,我就可以打印我的结果了。我收到此错误“TypeError: can only concatenate str (not "int") to str" 然后将 str() 添加到我的 for 循环中的 i 并收到以下错误“TypeError: cannot unpack non-iterable int object”

【问题讨论】:

  • 你能提供一些joined_groc_lstjoined_util_lst的值吗?

标签: python python-3.x dataframe dictionary


【解决方案1】:
total_joined_list=[joined_groc_lst,joined_util_lst]

groc_amount, util_amount = (abs(round(df.loc[df['Description'].str.contains(f'\b{e}\b',na=False),'Amount'].sum(),2))  for e in total_joined_list)

我已将您的 forloop 更改为一个生成器,该生成器允许解包数据以获取列表中的每个项目。

【讨论】:

  • 它给了我一个类型错误“TypeError: cannot unpack non-iterable float object”
  • 好的,我理解你的错误,我会编辑答案
  • @NickBosio 更好吗?
  • 我很高兴听到这个消息!随意接受我的回答。 stackoverflow.com/help/someone-answers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2013-06-05
  • 1970-01-01
  • 2020-08-13
相关资源
最近更新 更多