Python reads the data from the text and translates it into an instance of Dataframe _python

Source: Internet
Author: User
This article is to share with you that Python reads the data from the text and transforms it into an instance of Dataframe, which has a certain reference value, hoping to help people in need

In the technical question and answer to see a question like this, feel relatively common, just open an article write down.

Reads the data from the plain text format file "File_in" in the following format:

The output needs to be "file_out" in the following format:

The original format of the data is "Category: Content", with a blank line "\ n" as a sub-entry, converted into an entry line, in order to write the contents in sequence.

After reading, use pandas to set up the data called Dataframe form. This facilitates processing of data later. But the original format is not the usual table format, so do some simple processing first.

#coding: Utf8import sysfrom Pandas import DataFrame  #DataFrame通常来装二维的表格import pandas as PD      #pandas是流行的做数据分析的包 # The dictionary is created, and the keys and values are read from the file. The key is Nam,age ..., the value is lili,jim......dict_data={} #打开文件with open (' File_in.txt ', ' R ') as DF: #读每一行 for line  in  DF:    # If this line is a newline, skip it, use the length of ' \ n ' to find the empty line if    line.count (' \ n ') = = Len:      continue    #对每行清除前后空格 (if any), then use ":" To split    For KV in [Line.strip (). Split (': ')]:      #按照键, write the value in      dict_data.setdefault (kv[0],[]). Append (Kv[1]) #print (dict_ Data) Look at the effect # This is to read the key to become a list columnsname=list (Dict_data.keys ()) #建立一个DataFrame, the column name is the key name, that is Nam,age......frame = DataFrame ( Dict_data,columns=columnsname) #把DataFrame输出到一个表, do not line name and column name Frame.to_csv (' File_out0.txt ', index=false,header=false )

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.