簡體   English   中英

使用分隔符將文本發送到帶有 Pandas 的不同列

[英]Text to different columns with pandas using delimiters

我有一個很大的 excel 表格,其中包含關於不同人的同一單元格中的所有數據。 我已經拆分了數據,以便我有分隔符。 我用 (-) 來分隔不同的個體,並用 (;) 來分隔關於這些個體的信息。 我想使用這些分隔符將數據拆分為不同的列,但並非每個單元格都包含相同數量的人員信息,因此我無法使用固定數量的列。 我需要根據我擁有的數據創建一個數據框。

這是我的數據的示例: 在此處輸入圖片說明

如您所見,在每個單元格中列出了不同數量的人員。 我想要這樣的最終輸出: 在此處輸入圖片說明

人名總是跟在 (-) 之后,我只關心每個人的前三個數據,分別對應於 Name、Title 和 Email,其余的都是多余的。 我嘗試將文本添加到 excel 中的列中,但它刪除了大部分行。 另外,我嘗試用正則表達式按分隔符拆分,但我不能在多列中進行拆分,因為我必須分隔列數。

因此,我需要一個代碼來遍歷所有行,按 (-) 拆分信息並將第一個字符串定位在第一列中的 (-) 之后,第二列中定位在 (;) 之后的第二個字符串,以及第三列中 (;) 之后的第三個字符串,依此類推。 由於某些單元格有一個成員而其他單元格有多個成員,因此這必須無限次地繼續。

謝謝

單挑。 如果您嘗試基於“-”進行分隔,請注意該字符也出現在其他地方,例如“聯合創始人”。 一種方法可能是首先處理這些實例,使得“-”只出現在名稱之前。 正如您提到的,您想要一個 Pandas DataFrame,可以使用 apply 語句來格式化每一行的信息:

import itertools

import pandas as pd


def format_records(row):
    """Split records to construct DataFrame"""

    # Replace 'Co-Founder' with 'CoFounder'. The '-' will cause the split command to think Founder is someone's name
    row = row[0].replace('Co-Founder', 'CoFounder').replace('Co-founder', 'CoFounder')

    # Split each record (one per person) using '-' as the delimiter
    records = row.split('-')[1:]

    # Split data constituting each record by ';' and return the first three elements
    elements = [r.split(';')[:3] for r in records]

    # Construct new row by joining the first three elements of each record
    new_row = list(itertools.chain.from_iterable(elements))

    # Correct for the previous co-founder conversion
    new_row = [r.replace('CoFounder', 'Co-Founder') for r in new_row]

    # Convert to series
    new_series = pd.Series(new_row)

    return new_series


if __name__ == '__main__':
    # Read in data
    df = pd.read_excel('data.xlsx', header=None)

    # Re-organise data
    new_df = df.apply(format_records, axis=1)

    # Number of times the ['Name', 'Title', 'Email'] sequence should repeat (based on number of columns of new_df)
    repetitions = int(new_df.shape[1] / 3)

    # Add column names
    new_df.columns = ['Name', 'Title', 'Email'] * repetitions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM