如何将dict转换为datafram

2024-06-28 19:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

需要将字典转换为2列数据帧

这是我目前掌握的代码:

keywords= ["big","hat",'dress',"fabric","color"]

def keyword(value):
    keyword_counts = {key:0 for key in keywords}
    strings = value.split()
    for word in strings:
        if word in keyword_counts.keys():
          keyword_counts[word] += 1
    return keyword_counts

key_words_mo
result = keyword(key_words_mo)
print(result)

{'big': 0, 'hat': 0, 'dress': 26, 'fabric': 13, 'color': 9}

下面是我的问题,我需要下面的df来显示关键字的正确值。。。他们都说0例如“dress”应该表示26而不是0,“fabric”应该表示13而不是0。希望这两个列名分别称为“keyword\u term”和“quantity”

import pandas as pd
from ast import literal_eval
df = pd.DataFrame.from_dict(result, orient='index')
df

    0
big 0
hat 0
dress   0
fabric  0
color   0
while   0

Tags: keyindfforvaluehatresultkeyword
2条回答

您可以使用.count方法计算文本中出现的单词数:

import pandas as pd

def create_df(text, keywords):
  words = text.split()
  count = [words.count(key) for key in keywords]
  d = {'keyword_term': keywords, 'quantity': count}
  return pd.DataFrame.from_dict(d)

txt = "I was big and had a hat that dress dress fabric and not"
keywords= ["big","hat",'dress',"fabric","color"]
df = create_df(txt, keywords)
print(df)

试试这个:

d={'big':0,'hat':0,'dress':26,'fabric':13,'color':9}

df=pd.DataFrame(list(d.items()),columns=['keyword\u term','quantity'])

这会给你想要的

相关问题 更多 >