第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

CSV 到多值字典?

CSV 到多值字典?

尚方寶劍之說(shuō) 2022-06-22 15:40:21
                Title_1                                Title_2         Type He heard it from space  A quick story about sounds from space      Fiction    The end of all time       A sad poem about the end of time  Non-Fiction  The perfect beginning               A story about friendship  Non-Fiction我正在嘗試計(jì)算所有小說(shuō)、非小說(shuō)類型并計(jì)算 Title_1 和 Title_2 中相應(yīng)類型的單詞數(shù)。我想要的輸出是:Type         Count  Num-Words  Non-Fiction   2       20Fiction       1       12這是我到目前為止所擁有的:fopen =  open(file_name, 'r')fhand = csv.reader(fopen)next(fhand)category_sum = dict()for row in fhand:    col_0=len(row[0].split())    col_1=len(row[1].split())    print( col_1 + col_1)    if row[2] in category_sum.keys():        category_sum[row[2]]+=1    else:        category_sum[row[2]]=1我可以在一本不錯(cuò)的字典中獲得類型的總數(shù),但我似乎無(wú)法弄清楚如何將字?jǐn)?shù)分配給適當(dāng)?shù)念愋妥鳛樽值渲械闹?。有任何想法嗎?
查看完整描述

4 回答

?
小怪獸愛吃肉

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊

這就是我最終使用的:


fhand = csv.reader(fopen)

next(fhand)

category_sum = dict()

word_sum = dict()


for row in fhand:

    num_words = len(row[0].split(" ")) + len(row[1].split(" "))

    if row[2] in category_sum.keys():

        category_sum[row[2]]+=1

        word_sum[row[2]]+=num_words

    else:

        category_sum[row[2]]=1

        word_sum[row[2]]=num_words




combined = {key:[category_sum[key],word_sum[key]] for key in category_sum}   

#print(combined)

print("Category | # Titles | # of Words\n---------------------------------")

for key in combined:

    print("{}   |   {}  |   {}  ".format(key,combined[key][0],combined[key][1]))


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
MMMHUHU

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊

你可以這樣做:


import csv


file_name = 'book_titles.csv'


with open(file_name, 'r', newline='') as fopen:

    reader = csv.reader(fopen)

    next(reader)  # Skip header.

    category_sum = {}

    for row in reader:

        category_sum[row[2]] = category_sum.get(row[2], 0) + 1


print(category_sum)  # -> {'Fiction': 1, 'Non-Fiction': 2}


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
紅糖糍粑

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊

您可以將字典保存為其中一個(gè)鍵Count和另一個(gè)鍵所在的值Num-Words。因此,您的字典值分配可能如下所示:


# num_of_words = 

if row[2] in category_sum.keys():

    category_sum[row[2]]['Count']+=1

    category_sum[row[2]]['Num-Words']+=num_of_words

else:

    category_sum[row[2]]={}


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
蝴蝶不菲

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊

使用pandas

  • 創(chuàng)建數(shù)據(jù)框

  • 合并兩個(gè)標(biāo)題,按空格分割并計(jì)算由創(chuàng)建的列表中的單詞split

  • groupbyon Type,然后聚合countsum函數(shù)。

    • reset_indexrename獲得所需的確切形式。

import pandas as pd


# read the file in

df = pd.read_csv('file.csv')


                Title_1                                Title_2         Type

 He heard it from space  A quick story about sounds from space      Fiction

    The end of all time       A sad poem about the end of time  Non-Fiction

  The perfect beginning               A story about friendship  Non-Fiction


# count the words in Title_1 & Title_2

df['num_words'] = df[['Title_1', 'Title_2']].apply(lambda x: len(f'{x[0]} {x[1]}'.split()), axis=1)


                Title_1                                Title_2         Type  num_words

 He heard it from space  A quick story about sounds from space      Fiction         12

    The end of all time       A sad poem about the end of time  Non-Fiction         13

  The perfect beginning               A story about friendship  Non-Fiction          7


# create your desired output

test = df[['Type', 'num_words']].groupby('Type')['num_words'].agg(['count', 'sum']).reset_index().rename(columns={'count': 'Count', 'sum': 'Num-words'})


        Type  Count  Num-words

     Fiction      1         12

 Non-Fiction      2         20

只需 3 行代碼即可獲得所需的輸出

使用數(shù)據(jù)框中的數(shù)據(jù),如果需要,您可以更輕松地執(zhí)行其他類型的文本分析(例如文本分析:使用 python 查找列中最常見的單詞)

在 a 中獲取輸出dict:

test.to_dict('list')


>>> {'Type': ['Fiction', 'Non-Fiction'], 'Count': [1, 2], 'Num-words': [12, 20]}


查看完整回答
反對(duì) 回復(fù) 2022-06-22
  • 4 回答
  • 0 關(guān)注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)