df.loc在第一行上工作或不工作
我在“叙述”列中的数据是:
x 23
cricket 22
rev 11
polo 22
import os
import openpyxl
import pandas as pd
import numpy as np
narr=pd.read_csv('C:\\Users\\lenovo\\Desktop\\sports.csv')
narr.head(4)
df=pd.DataFrame(narr)
df.loc[(df.Narration == 'cricket') | (df.Narration == 'rev'), 'name_match'] = 'Match'
df.loc[(df.Narration == 'polo') | (df.Narration == 'x'), 'name_match'] = 'NotMatch'
print(df)
我要得到的结果是
Narration name_match
0 x 23 NaN
1 cricket 22 NaN
2 rev 11 NaN
3 polo 22 NaN
答案 0 :(得分:2)
IIUC,请尝试以下操作:
df.loc[df.Narration.str.contains('rev') |
df.Narration.str.contains('cricket'), 'name_match'] = 'Match'
df.loc[df.Narration.str.contains('polo') |
df.Narration.str.contains('x'), 'name_match'] = 'NotMatch'
df
输出:
Narration name_match
0 x 23 NotMatch
1 cricket 22 Match
2 rev 11 Match
3 polo 22 NotMatch