我每兩個DataFrames這些列['abstract', 'text', 'label']
,如果一個詞是在文本列dataframe1,用另一個替換詞,并作出新行新的資訊和添加dataframe2。對所有包含目標詞的行執行此操作。例如,如果列文本中有 'beautiful':
摘要:'123'
文字:'這是美好的一天'
標簽:'好'
然后制作以下資料并添加到其他DataFrame:
摘要:'bf'
文字:'這是一個 bf 日'
標簽:'美麗的'
uj5u.com熱心網友回復:
您可以使用熊貓的矢量化字串方法series.str.contains和series.str.replace:
import pandas as pd
df1 = pd.DataFrame({'abstract': ['123', 'other', 'more'],
'text': ['this is a beautiful day',
'this is not', 'beautiful too'],
'label': ['good', 'bad', 'good']})
df2 = pd.DataFrame(columns=df1.columns)
target = 'beautiful'
abbrev = 'bf'
new_rows = df1[df1.text.str.contains(target)].copy()
new_rows['abstract'] = abbrev
new_rows['text'] = new_rows.text.str.replace(target, abbrev)
new_rows['label'] = target
df2 = df2.append(new_rows)
df2
abstract text label
0 bf this is a bf day beautiful
2 bf bf too beautiful
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360950.html
上一篇:從多索引創建資料框
