python for文について
for文について
■文字列のカウント
df["CommentLen"]=df["Comment"].str.len() df
■文字列のカウント
# これはdf['Comment']の長さ=データ数である4が入ってしまう df['CommentLen'] = len(df['Comment']) df
■スライスの関数について
15文字までの文字列を抽出
・itertuplesを使う
slice_list=[] for row in df.itertuples(): slice_list.append(row.Comment[:15]) df["SlicedComment"]=slice_list
・applyを使う この処理は、一括処理されるため、forで繰り返しで処理するよりも実行速度が上がります。 Series.apply()に引数として実装した関数を渡すと、Seriesの各データが実装した関数の引数として渡された結果をシリーズとして返します。
def get_sliced_str(x): return x[:15] df["SlicedComment"]=df["Comment"].apply(get_sliced_str)
def get_3range_rate(x): if x >= 4: return '好評' elif x == 3: return '普通' elif x <= 2: return '不評' df['Rate3range'] = df['Rate'].apply(get_3range_rate)