3 回答

TA貢獻1943條經(jīng)驗 獲得超7個贊
從import re(您將使用它)開始。
然后創(chuàng)建你的數(shù)據(jù)框:
df = pd.DataFrame({
'file': ['abc.txt','abc.txt','ert.txt','ert.txt','ert.txt'],
'id': [1, 1, 2, 2, 2],
'book': ['Harry Potter', 'Vol 1', 'Lord of the Rings - Vol 1',
np.nan, 'Harry Potter']})
第一個處理步驟是添加一列,我們稱之為book2,其中包含下一行的book2:
df["book2"] = df.book.shift(-1).fillna('')
我添加fillna('')了用空字符串替換NaN值。
然后定義一個應(yīng)用于每一行的函數(shù):
def fn(row):
return f"{row.book} - {row.book2}" if row.book == 'Harry Potter'\
and re.match(r'^Vol \d+$', row.book2) else row.book
此函數(shù)檢查book == "Harry Potter" 和book2 是否匹配 "Vol" + 數(shù)字序列。如果是,則返回book + book2,否則僅返回book。
然后我們應(yīng)用這個函數(shù)并將結(jié)果保存在book下:
df["book"] = df.apply(fn, axis=1)
剩下的就是放棄:
book與Vol \d+匹配的行,
book2欄。
代碼是:
df = df.drop(df[df.book.str.match(r'^Vol \d+$').fillna(False)].index)\
.drop(columns=['book2'])
需要 fillna(False),因為str.match為源內(nèi)容返回NaN == NaN。

TA貢獻1820條經(jīng)驗 獲得超10個贊
假設(shè)“Vol x”出現(xiàn)在標(biāo)題后面的行上,我將使用通過將 book 列移動 -1 獲得的輔助系列。然后,將該 Series 與 book 列在它以 開頭時合并"Vol "并在 books 列以 開頭的位置放置行就足夠了"Vol "。代碼可以是:
b2 = df.book.shift(-1).fillna('')
df['book'] = df.book + np.where(b2.str.match('Vol [0-9]+'), ' - ' + b2, '')
print(df.drop(df.loc[df.book.fillna('').str.match('Vol [0-9]+')].index))
如果不能保證數(shù)據(jù)幀中的順序,但如果Vol x行與數(shù)據(jù)幀中具有相同文件和 id 的另一行匹配,則可以將數(shù)據(jù)幀分成兩部分,一個包含Vol x行,一個包含其他行并更新后者來自前者:
g = df.groupby(df.book.fillna('').str.match('Vol [0-9]+'))
for k, v in g:
if k:
df_vol = v
else:
df = v
for row in df_vol.iterrows():
r = row[1]
df.loc[(df.file == r.file)&(df.id==r.id), 'book'] += ' - ' + r['book']

TA貢獻1846條經(jīng)驗 獲得超7個贊
利用merge, apply, update, drop_duplicates.
set_index和merge上索引file,id的DF之間'Harry Potter'和df的'Vol 1'; join創(chuàng)建適當(dāng)?shù)淖址⑵滢D(zhuǎn)換為數(shù)據(jù)框
df.set_index(['file', 'id'], inplace=True)
df1 = df[df['book'] == 'Harry Potter'].merge(df[df['book'] == 'Vol 1'], left_index=True, right_index=True).apply(' '.join, axis=1).to_frame(name='book')
Out[2059]:
book
file id
abc.txt 1 Harry Potter Vol 1
更新原來df,drop_duplicate和reset_index
df.update(df1)
df.drop_duplicates().reset_index()
Out[2065]:
file id book
0 abc.txt 1 Harry Potter Vol 1
1 ert.txt 2 Lord of the Rings - Vol 1
2 ert.txt 2 NaN
3 ert.txt 2 Harry Potter
添加回答
舉報