パンダは、括弧の間のテキストを抽出し、テキストの各ビットの行を作成します

ATLの資金調達:

パンダでは、私は新しい列としてテキストことを角括弧と出力の間のテキストを抽出する必要がデータフレーム。私は「StudyID」レベルでこれを行うと、抽出されたテキストの各ビットのための新しい行を作成する必要があります。

ここでは単純化の例では、あるデータフレーム

data = {
    "studyid":['101', 
                '101', 
                '102', 
                '103'],
    "Question":["Q1",
                "Q2",
                "Q1",
                "Q3"],
    "text":['I love [Bananas] and also [oranges], and [figs]',
            'Yesterday I ate [Apples]',
            '[Grapes] are my favorite fruit',
            '[Mandarins] taste like [oranges] to me'],
}
df2 = pd.DataFrame(data)

私はそれが非常に長く、多くの手順であるが、(あなたがこれを実行する場合、それは、希望の出力を示し、下のコードを参照してください)ソリューションを働きました。私はこれを行うためのはるかに短い方法があるかどうかを知りたいと思っています。

あなたが、私は正規表現のためのstr.findallを()を使用していることがわかりますが、私はもともとデータフレームに抽出されたテキストを出力str.extractallを()しようとしたが、私は知りませんでしたどのように出力する「studyid」で抽出されたテキストextractall(によって生成されたデータフレームに含まれており、「質問」欄)。だから私はstr.findallを使用してに頼っ()。

ここに私のコードは(私はそれが不格好である知っている ')です - どのように私は、工程数を削減することができますか?あなたの助けを事前に感謝!

 # Step 1: Use Regex to pull put the text between the square brackets
df3 = pd.DataFrame(df2['text'].str.findall(r"(?<=\[)([^]]+)(?=\])").tolist())

  # Step 2: Merge the extracted text back with the original data
df3 = df2.merge(df3, left_index=True, right_index=True)

  # Step 3: Transpose the wide file to a long file (e.g. panel)
df4 = pd.melt(df3, id_vars=['studyid', 'Question'], value_vars=[0, 1, 2])

  # Step 4: Delete rows with None in the value column
indexNames = df4[df4['value'].isnull()].index
df4.drop(indexNames , inplace=True)

  # Step 5: Sort the data by the StudyID and Question
df4.sort_values(by=['studyid', 'Question'], inplace=True)

  # Step 6: Drop unwanted columns
df4.drop(['variable'], axis=1, inplace=True)

  # Step 7: Reset the index and drop the old index
df4.reset_index(drop=True, inplace=True)

df4
エズレル:

アサインバック出力した場合Series.str.findallに、列が使用可能性がありDataFrame.explode、ユニークインデックスの最後には、使用されDataFrame.reset_indexdrop=True

df2['text'] = df2['text'].str.findall(r"(?<=\[)([^]]+)(?=\])")

df4 = df2.explode('text').reset_index(drop=True)

ソリューションSeries.str.extractallの取り外しセカンドレベル、MultiIndexそして最後に使用しDataFrame.join、元に追加するために:

s = (df2.pop('text').str.extractall(r"(?<=\[)([^]]+)(?=\])")[0]
                   .reset_index(level=1, drop=True)
                   .rename('text'))

df4 = df2.join(s).reset_index(drop=True)

print (df4)
  studyid Question       text
0     101       Q1    Bananas
1     101       Q1    oranges
2     101       Q1       figs
3     101       Q2     Apples
4     102       Q1     Grapes
5     103       Q3  Mandarins
6     103       Q3    oranges

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=408452&siteId=1