Python 根据单词数将列拆分为未知数量的列-熊猫
我有一个熊猫数据框,其中一列包含一些字符串。我想根据字数将该列拆分为未知数量的列 假设我有数据帧Python 根据单词数将列拆分为未知数量的列-熊猫,python,pandas,Python,Pandas,我有一个熊猫数据框,其中一列包含一些字符串。我想根据字数将该列拆分为未知数量的列 假设我有数据帧df: Index Text 0 He codes 1 He codes well in python 2 Python is great language 3 Pandas package is very handy 现在我想把文本列分成多个列,每个列包含两个单词 Index 0
df
:
Index Text
0 He codes
1 He codes well in python
2 Python is great language
3 Pandas package is very handy
现在我想把文本列分成多个列,每个列包含两个单词
Index 0 1 2
0 He codes NaN NaN
1 He codes well in python
2 Python is great language NaN
3 Pandas package is very handy
如何在python中实现这一点?请帮忙。提前感谢。给定一个数据框
df
,其中在文本
列中,我们有需要拆分为两个单词的句子:
import pandas as pd
def splitter(s):
spl = s.split()
return [" ".join(spl[i:i+2]) for i in range(0, len(spl), 2)]
df_new = pd.DataFrame(df["Text"].apply(splitter).to_list())
# 0 1 2
# 0 He codes well None
# 1 He codes well in Python
IIUC,我们可以通过楼层分割和取消堆叠来进行str.split
groupby
cumcount
s = (
df["Text"]
.str.split("\s", expand=True)
.stack()
.to_frame("words")
.reset_index(1, drop=True)
)
s["count"] = s.groupby(level=0).cumcount() // 2
final = s.rename_axis("idx").groupby(["idx", "count"])["words"].agg(" ".join).unstack(1)
print(final)
count 0 1 2
idx
0 He codes NaN NaN
1 He codes well in python
2 Python is great language NaN
3 Pandas package is very handy
您确定给定的示例捕获了您所描述的内容吗?未知列数是什么意思?您的意思是
n
列数,即您可以设置和指定的列数。@DaveIdito根据未知的列数,我的意思是,如果任何句子最多包含10个字,则数据框将包含5个新列。我不知道一个句子可以包含的最大字数是多少,因为我将抓取网络数据。谢谢你的解决方案。如果我想将每列中的字数从2更改为任何其他数字,我应该做什么更改?然后,您必须调整拆分器
函数,并包括一个n
参数,然后替换该参数,而不是函数中的2。不要忘了在以后的函数调用中添加参数:)我会尽量避免使用apply
,它可能适用于小数据集,但不会扩展。尝试在pandas api中使用矢量化解决方案。见: