programing

문자열에서 판다 데이터 프레임 생성

randomtip 2023. 1. 5. 23:54
반응형

문자열에서 판다 데이터 프레임 생성

몇 가지 기능을 테스트하기 위해서DataFrame끈으로 묶어서테스트 데이터는 다음과 같습니다.

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

팬더에게 데이터를 읽어주는 가장 간단한 방법은 무엇일까요?DataFrame?

간단한 방법은 (python2) 또는 (python3)을 사용하여 함수에 전달하는 것입니다.예:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")

분할 방식

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)

한 줄에 있지만 먼저 IO 가져오기

import pandas as pd
import io   

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

df = pd.read_csv(io.StringIO(TESTDATA), sep=";")
print(df)

인터랙티브 작업을 위한 빠르고 쉬운 솔루션은 클립보드에서 데이터를 로드하여 텍스트를 복사하고 붙여넣는 것입니다.

마우스로 문자열 내용을 선택합니다.

Panda 데이터 프레임에 붙여넣기 위한 데이터 복사

Python 쉘에서 사용

>>> pd.read_clipboard()
  col1;col2;col3
0       1;4.4;99
1      2;4.5;200
2       3;4.7;65
3      4;3.2;140

적절한 구분 기호를 사용합니다.

>>> pd.read_clipboard(sep=';')
   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

>>> df = pd.read_clipboard(sep=';') # save to dataframe

이 답변은 문자열을 수동으로 입력할 때 적용되며, 어디서 읽었을 때는 적용되지 않습니다.

기존 변수 폭 CSV는 데이터를 문자열 변수로 저장하기 위해 읽을 수 없습니다.특히 실내에서 사용하는 경우.py파일 대신 파이프 너비로 구분된 고정 데이터를 고려하십시오.다양한 IDE 및 편집기에 파이프로 구분된 텍스트의 형식을 깔끔한 표로 지정하는 플러그인이 있을 수 있습니다.

사용법

예를 들어, 다음을 유틸리티 모듈에 저장합니다.util/pandas.py함수의 docstring에 예가 포함되어 있습니다.

import io
import re

import pandas as pd


def read_psv(str_input: str, **kwargs) -> pd.DataFrame:
    """Read a Pandas object from a pipe-separated table contained within a string.

    Input example:
        | int_score | ext_score | eligible |
        |           | 701       | True     |
        | 221.3     | 0         | False    |
        |           | 576       | True     |
        | 300       | 600       | True     |

    The leading and trailing pipes are optional, but if one is present,
    so must be the other.

    `kwargs` are passed to `read_csv`. They must not include `sep`.

    In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can 
    be used to neatly format a table.

    Ref: https://stackoverflow.com/a/46471952/
    """

    substitutions = [
        ('^ *', ''),  # Remove leading spaces
        (' *$', ''),  # Remove trailing spaces
        (r' *\| *', '|'),  # Remove spaces between columns
    ]
    if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
        substitutions.extend([
            (r'^\|', ''),  # Remove redundant leading delimiter
            (r'\|$', ''),  # Remove redundant trailing delimiter
        ])
    for pattern, replacement in substitutions:
        str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
    return pd.read_csv(io.StringIO(str_input), sep='|', **kwargs)

기능하지 않는 대체 수단

아래 코드는 왼쪽과 오른쪽 모두에 빈 열을 추가하기 때문에 제대로 작동하지 않습니다.

df = pd.read_csv(io.StringIO(df_str), sep=r'\s*\|\s*', engine='python')

에 대해서는read_fwf옵션인 kwargs를 실제로 많이 사용하지 않습니다.read_csv수용 및 사용.따라서 파이프 구분 데이터에는 전혀 사용하지 않아야 합니다.

오브젝트: 문자열을 데이터 프레임으로 만듭니다.

솔루션

def str2frame(estr, sep = ',', lineterm = '\n', set_header = True):
    dat = [x.split(sep) for x in estr.split(lineterm)][1:-1]
    cdf = pd.DataFrame(dat)
    if set_header:
        cdf = cdf.T.set_index(0, drop = True).T # flip, set ix, flip back
    return cdf

estr = """
sym,date,strike,genus
APPLE,20MAY20,50.0,Malus
ORANGE,22JUL20,50.0,Rutaceae
"""

cdf = str2frame(estr)

print(cdf)
0     sym     date strike     genus
1   APPLE  20MAY20   50.0     Malus
2  ORANGE  22JUL20   50.0  Rutaceae

언급URL : https://stackoverflow.com/questions/22604564/create-pandas-dataframe-from-a-string

반응형