Excel转Pajek可读文件格式(.net)Python实现
Excel轉(zhuǎn)Pajek可讀文件格式(.net)Python實(shí)現(xiàn)
第一次在CSDN寫東西,打開界面就喜歡上了,太優(yōu)秀了。。。
選修過復(fù)雜網(wǎng)絡(luò)課,中間需要將Excel數(shù)據(jù)轉(zhuǎn)為Pajek或是Gephi可讀的文件格式
- 一般Excel數(shù)據(jù)格式如下
| A1 | B1 | 100 |
| A2 | B2 | 50 |
| A3 | B3 | 80 |
- Pajek可讀文件格式如下
| 1 ‘‘A1’’ |
| 2 ‘‘A2’’ |
| 3 “A3” |
| 4 “B1” |
| 5 “B2” |
| 6 “B3” |
| *Edges |
| 1 4 100 |
| 2 5 50 |
| 3 6 80 |
直接上代碼吧
import xlrdworkbook = xlrd.open_workbook('C:\\Users\\X\\Desktop\\Pajek_FileType\\匯總.xlsx') booksheet = workbook.sheet_by_index(0) country_1 = booksheet.col_values(0, 1) #讀取第2行第1列開始的數(shù)據(jù) country_2 = booksheet.col_values(1, 1) #讀取第2行第2列開始的數(shù)據(jù) Volume_of_trade = booksheet.col_values(2, 1) #讀取第2行第2列開始的數(shù)據(jù)# 刪除重復(fù)項(xiàng) sum_country = [] dic=Counter(country_1 + country_2) sum_country=list(dic.keys()) ''' 第一次代碼,效率低,廢棄 for i in country_1:if i not in sum_country:sum_country.append(i) for i in country_2:if i not in sum_country:sum_country.append(i) ''' # 處理空數(shù)據(jù)為0 for i in range(len(Volume_of_trade)):if Volume_of_trade[i] == '':Volume_of_trade[i] = 0# 輸出文件階段 file_handle = open('C:\\Users\\X\\Desktop\\Pajek_FileType\\GlobalTrade.net',mode='w+') file_handle.write('{0} {1}\n'.format('*Vertices', len(sum_country))) tem_1 = 1 # 計(jì)數(shù)器 for i in sum_country:file_handle.write('{0} {1}\n'.format(tem_1, '\"'+i+'\"'))tem_1 += 1file_handle.write('*Edges\n') for i in range(len(country_1)):first = sum_country.index(country_1[i]) + 1second = sum_country.index(country_2[i]) + 1value = Volume_of_trade[i]file_handle.write('{0} {1} {2}\n'.format(str(first), str(second), str(value))) file_handle.close()運(yùn)行需要安裝xlrd包,有需求的可以在站內(nèi)搜搜大神的博客,寫得很詳細(xì),這里就不貼出來了。
第一次寫,就算記錄自己的成長(zhǎng)吧。非常小而且簡(jiǎn)單的一段代碼,但還是有不滿意的地方,比如一開始刪除重復(fù)項(xiàng),兩個(gè)for循環(huán)能不能優(yōu)化?format函數(shù)** { } ** 中的參數(shù)調(diào)試,讓輸出更好看。。。
歡迎大佬指教,也希望有共同愛好,喜歡代碼喜歡編程的朋友一起學(xué)習(xí)
改進(jìn) 2019.1.22
原代碼刪除重復(fù)項(xiàng)使用了兩個(gè)for循環(huán),這在實(shí)際運(yùn)用(數(shù)據(jù)量達(dá)到百萬(wàn)級(jí)別)將會(huì)耗費(fèi)大量時(shí)間,新的方法采用Counter函數(shù),該方法可以將對(duì)列表元素進(jìn)行統(tǒng)計(jì),返回一個(gè)字典對(duì)象,其速度較之前的方法提升非常巨大
原代碼效:
輸出為:
改進(jìn)代碼條件下:
輸出為:
原文件中僅僅有4W條數(shù)據(jù),通過改進(jìn)的方法,速度提升幾十倍
第一個(gè)博客,返回來看有點(diǎn)簡(jiǎn)陋,代碼問題很多,各方面都有點(diǎn)不全面。會(huì)努力學(xué)習(xí),能做到完美的話盡力達(dá)到,展現(xiàn)更好的給愛好編程,愛好專研的朋友們。
持續(xù)更新。。。
總結(jié)
以上是生活随笔為你收集整理的Excel转Pajek可读文件格式(.net)Python实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 武钢员工安全手册_员工如何成为您最大的网
- 下一篇: pajek15-18:网络