<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python處理CSV、JSON和XML數(shù)據(jù)的簡(jiǎn)便方法來(lái)了

          共 4316字,需瀏覽 9分鐘

           ·

          2021-11-12 15:46


          Python的卓越靈活性和易用性使其成為最受歡迎的編程語(yǔ)言之一,尤其是對(duì)于數(shù)據(jù)處理和機(jī)器學(xué)習(xí)方面來(lái)說(shuō),其強(qiáng)大的數(shù)據(jù)處理庫(kù)和算法庫(kù)使得python成為入門數(shù)據(jù)科學(xué)的首選語(yǔ)言。在日常使用中,CSV,JSON和XML三種數(shù)據(jù)格式占據(jù)主導(dǎo)地位。下面我將針對(duì)三種數(shù)據(jù)格式來(lái)分享其快速處理的方法。


          CSV數(shù)據(jù)

          CSV是存儲(chǔ)數(shù)據(jù)的最常用方法。在Kaggle比賽的大部分?jǐn)?shù)據(jù)都是以這種方式存儲(chǔ)的。我們可以使用內(nèi)置的Python csv庫(kù)來(lái)讀取和寫入CSV。通常,我們會(huì)將數(shù)據(jù)讀入列表列表。

          看看下面的代碼。當(dāng)我們運(yùn)行csv.reader()所有CSV數(shù)據(jù)變得可訪問(wèn)時(shí)。該csvreader.next()函數(shù)從CSV中讀取一行;?每次調(diào)用它,它都會(huì)移動(dòng)到下一行。我們也可以使用for循環(huán)遍歷csv的每一行for row in csvreader 。確保每行中的列數(shù)相同,否則,在處理列表列表時(shí),最終可能會(huì)遇到一些錯(cuò)誤。


          import?csv?

          filename?=?"my_data.csv"

          fields?=?[]?
          rows?=?[]???
          #?Reading?csv?file?
          with?open(filename,?'r')?as?csvfile:?
          ????#?Creating?a?csv?reader?object?
          ????csvreader?=?csv.reader(csvfile)?

          ????#?Extracting?field?names?in?the?first?row?
          ????fields?=?csvreader.next()?

          ????#?Extracting?each?data?row?one?by?one?
          ????for?row?in?csvreader:?
          ????????rows.append(row)??
          #?Printing?out?the?first?5?rows?
          for?row?in?rows[:5]:?
          ????print(row)


          在Python中寫入CSV同樣容易。在單個(gè)列表中設(shè)置字段名稱,并在列表列表中設(shè)置數(shù)據(jù)。這次我們將創(chuàng)建一個(gè)writer()對(duì)象并使用它將我們的數(shù)據(jù)寫入文件,與讀取時(shí)的方法基本一樣。


          import?csv?

          #?Field?names?
          fields?=?['Name',?'Goals',?'Assists',?'Shots']?

          #?Rows?of?data?in?the?csv?file?
          rows?=?[?['Emily',?'12',?'18',?'112'],?
          ?????????['Katie',?'8',?'24',?'96'],?
          ?????????['John',?'16',?'9',?'101'],?
          ?????????['Mike',?'3',?'14',?'82']]

          filename?=?"soccer.csv"

          #?Writing?to?csv?file?
          with?open(filename,?'w+')?as?csvfile:?
          ????#?Creating?a?csv?writer?object?
          ????csvwriter?=?csv.writer(csvfile)?

          ????#?Writing?the?fields?
          ????csvwriter.writerow(fields)?

          ????#?Writing?the?data?rows?
          ????csvwriter.writerows(rows)


          我們可以使用Pandas將CSV轉(zhuǎn)換為快速單行的字典列表。將數(shù)據(jù)格式化為字典列表后,我們將使用該dicttoxml庫(kù)將其轉(zhuǎn)換為XML格式。我們還將其保存為JSON文件!


          import?pandas?as?pd
          from?dicttoxml?import?dicttoxml
          import?json

          #?Building?our?dataframe
          data?=?{'Name':?['Emily',?'Katie',?'John',?'Mike'],
          ????????'Goals':?[12,?8,?16,?3],
          ????????'Assists':?[18,?24,?9,?14],
          ????????'Shots':?[112,?96,?101,?82]
          ????????}

          df?=?pd.DataFrame(data,?columns=data.keys())

          #?Converting?the?dataframe?to?a?dictionary
          #?Then?save?it?to?file
          data_dict?=?df.to_dict(orient="records")
          with?open('output.json',?"w+")?as?f:
          ????json.dump(data_dict,?f,?indent=4)

          #?Converting?the?dataframe?to?XML
          #?Then?save?it?to?file
          xml_data?=?dicttoxml(data_dict).decode()
          with?open("output.xml",?"w+")?as?f:
          ????f.write(xml_data)


          JSON數(shù)據(jù)

          JSON提供了一種簡(jiǎn)潔且易于閱讀的格式,它保持了字典式結(jié)構(gòu)。就像CSV一樣,Python有一個(gè)內(nèi)置的JSON模塊,使閱讀和寫作變得非常簡(jiǎn)單!我們以字典的形式讀取CSV時(shí),然后我們將該字典格式數(shù)據(jù)寫入文件。


          import?json
          import?pandas?as?pd

          #?Read?the?data?from?file
          #?We?now?have?a?Python?dictionary
          with?open('data.json')?as?f:
          ????data_listofdict?=?json.load(f)

          #?We?can?do?the?same?thing?with?pandas
          data_df?=?pd.read_json('data.json',?orient='records')

          #?We?can?write?a?dictionary?to?JSON?like?so
          #?Use?'indent'?and?'sort_keys'?to?make?the?JSON
          #?file?look?nice
          with?open('new_data.json',?'w+')?as?json_file:
          ????json.dump(data_listofdict,?json_file,?indent=4,?sort_keys=True)

          #?And?again?the?same?thing?with?pandas
          export?=?data_df.to_json('new_data.json',?orient='records')


          正如我們之前看到的,一旦我們獲得了數(shù)據(jù),就可以通過(guò)pandas或使用內(nèi)置的Python CSV模塊輕松轉(zhuǎn)換為CSV。轉(zhuǎn)換為XML時(shí),可以使用dicttoxml庫(kù)。具體代碼如下:


          import?json
          import?pandas?as?pd
          import?csv

          #?Read?the?data?from?file
          #?We?now?have?a?Python?dictionary
          with?open('data.json')?as?f:
          ????data_listofdict?=?json.load(f)

          #?Writing?a?list?of?dicts?to?CSV
          keys?=?data_listofdict[0].keys()
          with?open('saved_data.csv',?'wb')?as?output_file:
          ????dict_writer?=?csv.DictWriter(output_file,?keys)
          ????dict_writer.writeheader()
          ????dict_writer.writerows(data_listofdict)


          XML數(shù)據(jù)

          XML與CSV和JSON有點(diǎn)不同。CSV和JSON由于其既簡(jiǎn)單又快速,可以方便人們進(jìn)行閱讀,編寫和解釋。而XML占用更多的內(nèi)存空間,傳送和儲(chǔ)存需要更大的帶寬,更多存儲(chǔ)空間和更久的運(yùn)行時(shí)間。但是XML也有一些基于JSON和CSV的額外功能:您可以使用命名空間來(lái)構(gòu)建和共享結(jié)構(gòu)標(biāo)準(zhǔn),更好地傳承,以及使用XML、DTD等數(shù)據(jù)表示的行業(yè)標(biāo)準(zhǔn)化方法。

          要讀入XML數(shù)據(jù),我們將使用Python的內(nèi)置XML模塊和子模ElementTree。我們可以使用xmltodict庫(kù)將ElementTree對(duì)象轉(zhuǎn)換為字典。一旦我們有了字典,我們就可以轉(zhuǎn)換為CSV,JSON或Pandas Dataframe!具體代碼如下:


          import?xml.etree.ElementTree?as?ET
          import?xmltodict
          import?json

          tree?=?ET.parse('output.xml')
          xml_data?=?tree.getroot()

          xmlstr?=?ET.tostring(xml_data,?encoding='utf8',?method='xml')


          data_dict?=?dict(xmltodict.parse(xmlstr))

          print(data_dict)

          with?open('new_data_2.json',?'w+')?as?json_file:
          ????json.dump(data_dict,?json_file,?indent=4,?sort_keys=True)


          原文參考

          https://towardsdatascience.com/the-easy-way-to-work-with-csv-json-and-xml-in-python-5056f9325ca9



          安裝圖文并茂,插件體驗(yàn)超棒,VScode詳細(xì)教程來(lái)了!


          最近發(fā)布的 Python 3.10 中的 Match-Case,其實(shí)沒(méi)那么簡(jiǎn)單


          真香啊,20張高清數(shù)據(jù)分析全知識(shí)地圖,要學(xué)的東西全都概況了


          長(zhǎng)按或掃描下方二維碼,后臺(tái)回復(fù):加群,可申請(qǐng)入群。一定要備注:入群+地點(diǎn)+學(xué)習(xí)/公司。例如:入群+上海+復(fù)旦。


          感謝你的分享,點(diǎn)贊,在看??

          瀏覽 57
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产65一二三区 | 91亚洲国产成人久久精品网 | 啊v视频| 成人性爱视频免费网站 | 在线视频黄色国产 |