所以我有這個資料集,它在“a”列上有一些 nan 值。我只需要替換列“a”的 nan 值,并在 b 列的行上應用正則運算式,并計算其值上的主題標簽數量。因為我有一個非常大的資料集,所以我需要就地進行。
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [0, np.nan, np.nan], 'b': ["#hello world", "#hello #world", "hello #world"]})
print(df)
結果應該是
df = pd.DataFrame({'a': [0, 2, 1], 'b': ["#hello world", "#hello #world", "hello #world"]})
print(df)
我已經有了正則運算式方法
regex_hashtag = "#[a-zA-Z0-9_] "
num_hashtags = len(re.findall(regex_hashtag, text))
我該怎么做?
uj5u.com熱心網友回復:
使用str.count:
regex_hashtag = "#[a-zA-Z0-9_] " # or '#\w '
m = df['a'].isna()
df.loc[m, 'a'] = df.loc[m, 'b'].str.count(regex_hashtag)
輸出:
a b
0 0 #hello world
1 2 #hello #world
2 1 hello #world
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/521238.html
標籤:Python熊猫呐
