본문 바로가기

파이썬

데이터프레임에서 열 크기를 정하고 열 크기를 벗어나는 문자수가 있다면 행을 늘려 모든 문자를 나타낼 수 있는 코드

728x90
반응형

안타깝게도, 이것은 내용물의 길이에 따라 서식을 지정하거나 행의 크기를 변경하는 것을 처리하도록 제작되지 않았기 때문에 판다에서 간단한 작업이 아닙니다. 이에 접근하는 한 가지 방법은 열의 셀에 대해 수동으로 반복하고 셀의 길이를 확인하는 것입니다. 셀의 길이가 지정된 열 크기보다 클 경우, 텍스트를 여러 행으로 분할하여 동일한 열에 있는 여러 셀에 분산시킬 수 있습니다. 이를 달성하기 위한 코드의 예는 다음과 같습니다:

import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'Column 1': ['This is a long text', 'This is another long text', 'This is a short text']})

# Specify the maximum column size
max_column_size = 15

# Create an empty list to store the modified data
mod_data = []

# Iterate over the rows in the dataframe
for i, row in df.iterrows():
    col1 = row['Column 1']
    # If the length of the text in the cell is greater than max_column_size
    if len(col1) > max_column_size:
        # Split the text into multiple parts
        parts = [col1[j:j+max_column_size] for j in range(0, len(col1), max_column_size)]
        # Add each part as a separate row in the mod_data list
        for part in parts:
            mod_data.append({'Column 1': part})
    else:
        # If the length of the text is less than or equal to max_column_size, add the row to the mod_data list
        mod_data.append({'Column 1': col1})

# Create a new dataframe from the modified data
mod_df = pd.DataFrame(mod_data)

위 코드는 데이터 프레임 df의 열 1에 있는 셀을 max_column_size(이 경우 15)보다 큰 텍스트 길이를 가진 여러 셀로 분할합니다. 수정된 데이터는 mod_data 목록에 저장되며, 이 목록은 새 데이터 프레임 mod_df를 만드는 데 사용됩니다

728x90
반응형