【发布时间】:2019-10-31 14:09:39
【问题描述】:
由于 MS Excel 将单元格中的字符数限制为 32767,因此我必须将 pandas 数据框中的较长字符串拆分为多个单元格。
有没有办法将 pandas 列“Text”的字符串拆分为几列“Text_1”、“Text_2”、“Text_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 列相应地拆分为以下内容:
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()
【问题讨论】:
标签: regex python-3.x string pandas