【问题标题】:How can I split the output of str.split() column in pandas?如何在熊猫中拆分 str.split() 列的输出?
【发布时间】:2021-08-07 04:48:38
【问题描述】:

事情是这样的,我有这样的数据集(我们称之为 df):

id       text
A1       How was your experience?: Great\nWhat did you buy?: A book\n
B1       How was your experience?: Good\nWhat did you buy?: A pen\n
C2       How was your experience?: Awful\nWhat did you buy?: A pencil\n

如您所见,这是一个包含调查的表格,我试图仅从列文本中获取答案。我的第一个挑战是尝试拆分文本,就像这样:

df['text_splitted'] = df.text.str.split('\n')

然后我会做这样的事情:

df['final_text'] = df. text_splitted.str.split(':')

但是,final_text 正在返回 NaN。刚刚发生了什么?为什么新列返回 null?有什么方法可以解决这个问题(或者更好的方法来做我想做的事情)?

【问题讨论】:

  • 因为df['text_splitted']不是字符串而是列表(split)
  • @Corralien 在列表中使用 .str.split(':') 是正确的,这将导致 null/NaN。然而,为了改进这个和未来的问题,您的数据应该是一段易于可复制的代码,可用于轻松构建您的数据框。请参阅 MRE - Minimal, Reproducible, ExampleHow to make good reproducible pandas examples。如果您包含预期的输出,那么您可能不仅会找到出错的地方,而且还会找到可行的解决方案。

标签: python pandas string split


【解决方案1】:

您可以结合使用 .apply() 和 .split() 来获得答案

df = pd.DataFrame({'text': ['How was your experience?: Great\nWhat did you buy?: A book\n']})

输入 DF

    text
0   How was your experience?: Great\nWhat did you ..

分成问题和答案

df['questions'] = df['text'].apply(lambda x: [y.split(":")[0] for y in x.split("\n")])
df['answers'] = df['text'].apply(lambda x: [y.split(":")[1] for y in x.split("\n") if len(y)>1])

输出DF

    answers              questions
0   [ Great, A book]    [How was your experience?, What did you buy?, ]

【讨论】:

  • 不确定为什么答案会返回“IndexError: list index out of range”。有什么想法吗?
【解决方案2】:

正如您所写,您需要将您的列text 拆分两次。之后,您可以创建一个包含 3 列的数据框:

  • id 来自您的原始数据框
  • question(偶数行)来自上一次拆分
  • answer(奇数行)来自上一次拆分
text = df["text"].str.strip().str.split("\n").explode().str.split(": ").explode()

out = pd.merge(df["id"], pd.DataFrame({"question": text[0::2], "answer": text[1::2]}),
               left_index=True, right_index=True).reset_index(drop=True)

您如何看待这种格式?

>>> out
   id                  question    answer
0  A1  How was your experience?     Great
1  A1         What did you buy?    A book
2  B1  How was your experience?      Good
3  B1         What did you buy?     A pen
4  C2  How was your experience?     Awful
5  C2         What did you buy?  A pencil

【讨论】:

    【解决方案3】:

    你可以试试这个:

    df.set_index('id')['text'].str.replace(r'\\n$', '').str.split(r'\\n').explode().str.split(': ', expand=True)
    
                               0         1
    id                                    
    A1  How was your experience?     Great
    A1         What did you buy?    A book
    B1  How was your experience?      Good
    B1         What did you buy?     A pen
    C2  How was your experience?     Awful
    C2         What did you buy?  A pencil
    

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 2023-03-16
      • 2019-10-21
      • 1970-01-01
      相关资源
      最近更新 更多