基于“column_name”中的文本,我想在一個新列中創建一行,該行回傳與“column_name”中找到的文本關聯的字串。這是代碼:
temp_2 = []
for index,row in df2.iterrows():
if 'abc' in row['column_name']:
temp_2.append('A')
elif 'def'in row['column_name']:
temp_2.append('B')
elif 'ghk'in row['column_name']:
temp_2.append('C')
else:
temp_2.append('Other')
df2['Temp_2'] = temp_2
df2
Python 回傳:
/tmp/ipykernel_33624/2126258456.py:20: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df2['Temp_2'] = temp_2
如何修改代碼以洗掉警告?
uj5u.com熱心網友回復:
對于洗掉警告:-)
import warnings
warnings.filterwarnings("ignore")
對于更簡潔的代碼,你可以試試這個:-)
df['Temp_2']='Other'
df['Temp_2'][df.column_name.str.contains('abc')]='A'
df['Temp_2'][df.column_name.str.contains('def')]='B'
df['Temp_2'][df.column_name.str.contains('ghk')]='C'
df
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427743.html
上一篇:R計算中的for回圈錯誤結果
下一篇:創建遍歷兩個串列的新串列
