python - 将包含字符串和整数值的元组中的值组合起来并存储为数据帧

标签 python dataframe type-conversion tuples

我正在构建一个函数,该函数接受公司描述列表,然后输出列表中最常见的三词短语。我已经能够让它输出这样构造的元组字典:

{('technology', 'company', 'provides'): 2,
 ('various', 'industries.', 'company'): 2,
 ('provides', 'software', 'solutions'): 2,
 ('life', 'health', 'insurance'): 2,...}

我想将其转换为表/数据框,将字符串连接成单个值,然后创建一个单独的列来存储该短语的实例数。

理想的输出是:

<表类=“s-表”> <标题> 短语 发生 <正文> 科技公司提供 2 各行业公司 2 提供软件解决方案 2 人寿健康保险 2

我尝试使用以下方法将元组组合成一个字符串,但它会减少出现的次数:

# function that converts tuple to string
def join_tuple_string(descriptions) -> str:
   return ' '.join(descriptions)

# joining all the tuples
result = map(join_tuple_string, descriptions)

# converting and printing the result
print(list(result))

这是输出:

['technology company provides', 
'provides software solutions', 
'product suite includes', 'life health insurance',...]

如何连接这些值而不丢失出现次数?我希望能够将其导出到 CSV 以查看完整列表。

最佳答案

import pandas as pd

result = {('technology', 'company', 'provides'): 2,
 ('various', 'industries.', 'company'): 2,
 ('provides', 'software', 'solutions'): 2,
 ('life', 'health', 'insurance'): 2}

df = pd.DataFrame(result.items(), columns=['phrase', 'occurrence'])
df.phrase = df.phrase.str.join(' ')
print(df)
df.to_csv('phrases.csv', index=False)

df 输出:

                        phrase  occurrence
0  technology company provides           2
1  various industries. company           2
2  provides software solutions           2
3        life health insurance           2

csv 文件:

phrase,occurrence
technology company provides,2
various industries. company,2
provides software solutions,2
life health insurance,2

关于python - 将包含字符串和整数值的元组中的值组合起来并存储为数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69866261/

相关文章:

python - 使用 PCA 时出现数学域错误

python - 如果不存在python,如何在CREATE TABLE中更改名称

python - 如何确定我在 Mac OSX 上正确安装了 pip?

python - 具有相同列名的内部合并数据帧并应用聚合函数

java - 基于Java DataFrame去除重复行

apache-spark - 在 Spark 中使用相应的列名称(有条件地)更改数据框

sql - Postgres : integer out of range. 为什么会出现这个错误?

c - 将 char 存储在 char [] 中可以从指针生成整数而无需强制转换?

java - 在 CORBA 客户端/服务器应用程序中将 unsigned long(从 C++)分配给 long(Java)?

python - Python 函数 scipy.sparse.bmat 的 R 等价物是什么?