【问题标题】:Split column into unknown number of columns according to number of words- Pandas根据字数将列拆分为未知数量的列-Pandas
【发布时间】:2020-06-29 18:14:30
【问题描述】:

我有一个熊猫数据框,其中一列包含一些字符串。我想根据字数将该列拆分为未知数量的列。

假设,我有 DataFrame df

Index        Text
0          He codes
1          He codes well in python
2          Python is great language
3          Pandas package is very handy 

现在我想将文本列分成多列,每列包含 2 个单词。

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 中做到这一点?请帮忙。提前致谢。

【问题讨论】:

  • 您确定给定的示例符合您的描述吗?
  • 未知列数是什么意思?您的意思是n 列数,即您可以设置和指定的列数。
  • @DaveIdito 通过未知的列数,我的意思是如果任何句子最多包含 10 个单词,那么数据框将包含 5 个新列。我不知道一个句子最多可以包含多少个单词,因为我会抓取网络数据。

标签: python pandas


【解决方案1】:

给定一个数据框df,其中Text 列中的句子需要被两个单词分割:

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

【讨论】:

  • 感谢您的解决方案。如果我想将每列中的单词数从 2 更改为任何其他数字,我应该进行哪些更改?
  • 然后您必须调整 splitter 函数并包含一个 n 参数,然后替换该参数而不是函数中的 2。不要忘记稍后将参数添加到函数调用中:)
  • 我会尽量避免使用apply,它可能适用于小型数据集,但无法扩展。尝试在 pandas api 中使用矢量化解决方案。见:Should I ever use Apply
【解决方案2】:

IIUC,我们可以str.splitgroupbycumcount有楼层划分和unstack

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    相关资源
    最近更新 更多