【问题标题】:Joining excel rows to a single string to be used in pandas DataFrame将 excel 行连接到要在 pandas DataFrame 中使用的单个字符串
【发布时间】:2020-01-06 16:31:34
【问题描述】:

我是 Pandas 的新手。

我有一个 excel 文件,里面有 10 张纸。我正在尝试to achieve this

由于没有提供关于该问题的答案,我将使用此方法检查 DataFrame 行中的字符串是否包含 excel 表中的单词:

file = pd.read_excel(open('config_values.xlsx', 'rb'),
                     sheet_name='ContainsFree')
  1. 使用first_sheet = '|'.join(file)加入Excel工作表中的所有行

  2. 使用:

df['Contains Language'] = df.Search_Query.str.contains(first_sheet, regex=True)

但是,当我使用 '|'.join(file) 时,我得到的是 excel 表的第一行而不是连接的字符串:

excel_sheet_1

gratuit
free
gratis
...

'|'join.(file) 之后我得到:

gratuit

预期:

gratuit|free|gratis

为了加入 Excel 工作表中的所有行,我做错了什么?

感谢您的建议。

【问题讨论】:

  • 使用read_excel时不需要open
  • 谢谢,但我仍然无法使用 '|'.join(file) 将所有行加入到单个字符串中,我只能获得工作表的第一个条目。

标签: python excel pandas


【解决方案1】:

试试:

file = pd.read_excel('config_values.xlsx', sheet_name='ContainsFree', header=None)
'|'.join(file[0].astype(str))

'gratuit|free|gratis'

【讨论】:

  • 成功了,刚刚添加了file = '|'.join(file[0]),谢谢。
  • 您介意加入ints吗?我得到一个错误:TypeError: sequence item 0: expected str instance, int found,当我使用containsYear = '|'.join(str(containsYear[0])) 时,我得到0| | | | | |2|0|1|0|。当我尝试加入2001,2002,2003,...
  • @JonasPalačionis 我编辑了我的答案。尝试添加astype(str)
猜你喜欢
  • 2021-05-12
  • 2016-06-25
  • 2015-02-02
相关资源
最近更新 更多