Разделение длинной строки в ячейке панд рядом с положением n-го символа на несколько ячеек без разделения слов - PullRequest
1 голос
/ 31 октября 2019

Поскольку MS Excel ограничивает количество символов в ячейке до 32767, мне приходится разбивать более длинные строки в кадре данных панд на несколько ячеек.

Есть ли способ разбить строки столбца панд "Текст" на несколько столбцов "Текст_1", "Текст_2", "Текст_3", ..., чтобы разделить? Также важно, чтобы текстовый блок не был разделен внутри слова, поэтому я предполагаю, что необходимо регулярное выражение.

Пример кадра данных:

df_test = pd.DataFrame({'Text' : ['This should be the first very long string','This is the second very long string','This is the third very long string','This is the last string which is very long'],
               'Date' : [2019, 2018, 2019, 2018],
               'Source' : ["FAZ", "SZ" , "HB", "HB"],
               'ID' : ["ID_1", "ID_2", "ID_3", "ID_4"]})
df_test

    Text                                        Date    Source  ID
0   This should be the first very long string   2019    FAZ     ID_1
1   This is the second very long string         2018    SZ      ID_2
2   This is the third very long string          2019    HB      ID_3
3   This is the last string which is very long  2018    HB      ID_4

Предполагая, что вырезка в этом примере происходит приn=15, а не на n=32767, я хочу разделить столбец Текст соответственно на что-то вроде этого:

    Text_1          Text_2          Text_3         Text_4      Date   Source    ID
0   This should be  the first very  long string                2019   FAZ       ID_1
1   This is the     second very     long string                2018   SZ        ID_2
2   This is the     third very long  string                    2019   HB        ID_3
3   This is the     last string     which is very  long        2018   HB        ID_4

В конечном итоге подход должен масштабироваться до n=32767 и по крайней мере до десяти новых столбцов "Text_1", "Text_2" и т. Д.

До сих пор я создал новый столбец "n", указывающий длину df_text["Text"] строк в строке:

df_test['n'] = df_test['Text'].str.split("").str.len()

Ответы [ 2 ]

1 голос
/ 31 октября 2019

Вот общая идея.

# find longest long string, then divide the text 
# into the number of new cols you want, adding a | at
# the division and then later splitting by that |

longest = ""
for x in df_test['Text']:
    if len(x) > len(longest):
        longest = x
    continue

import math 

num_cols = math.floor(len(longest.split(' ')) / 3) # shoot for 3 words per row
for index,row in df_test.iterrows():

    word_str = row['Text']
    word_char_len = len(word_str)
    word_as_list = word_str.split(' ')
    num_words = len(word_as_list)

    col_index = math.ceil(len(word_as_list) / num_cols)

    for _ in range(num_cols - 1):
        word_as_list.insert(col_index,'|')
        col_index += col_index
    new = ' '.join(word_as_list)
    df_test.at[index,'Text'] = new

cols = ['Text'+str(i) for i in range(1,num_cols+1)]
df_test[cols] = df_test.Text.str.split('|',expand=True)
del df_test['Text']                                                                                                                   
print(df_test)

ВЫХОД

   Date Source    ID            Text1          Text2                Text3
0  2019    FAZ  ID_1  This should be      the first      very long string
1  2018     SZ  ID_2     This is the    second very           long string
2  2019     HB  ID_3     This is the     third very           long string
3  2018     HB  ID_4     This is the    last string    which is very long

Я загрузу полную, когда я закончу. Прокомментируйте, если вам не нравится этот способ или у вас есть другие предложения.

0 голосов
/ 31 октября 2019

Да - одна ячейка панды должна содержать максимальное количество символов 32767. Поэтому строка из df_test [«Text»] должна быть соответственно разделена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...