pandas:如何使用字典更新匹配行而不进行迭代
我有一个数据帧:pandas:如何使用字典更新匹配行而不进行迭代,pandas,Pandas,我有一个数据帧: data = [{'car' :'audi','year':2001,'wheel':4}, {'car' :'honda','year':2002,'wheel':15}, {'car' :'tesla','year':2003,'wheel':5}] df = pd.DataFrame(data) df.set_index('car',inplace=True) 我使用字典筛选dataframe以获得匹配行: filtObj = {'y
data = [{'car' :'audi','year':2001,'wheel':4},
{'car' :'honda','year':2002,'wheel':15},
{'car' :'tesla','year':2003,'wheel':5}]
df = pd.DataFrame(data)
df.set_index('car',inplace=True)
我使用字典筛选dataframe以获得匹配行:
filtObj = {'year':2002,'wheel':15}
dfMatched = df.loc[(df[list(filtObj)] == pd.Series(filtObj)).all(axis=1)]
Q) 找到匹配项后,如何仅使用更新字典中指定的键、值对更新匹配项
updateObj = {'year':2020}
dfMatched.update(updateObj)
与使用字典创建的DataFrame
一起使用,并与筛选索引一起使用,以便按掩码进行匹配:
filtObj = {'year':2002,'wheel':15}
m = (df[list(filtObj)] == pd.Series(filtObj)).all(axis=1)
updateObj = {'year':2020}
df.update(pd.DataFrame(updateObj, index=df.index[m]))
print (df)
year wheel
car
audi 2001.0 4
honda 2020.0 15
tesla 2003.0 5
与使用字典创建的DataFrame
一起使用,并与筛选索引一起使用,以便按掩码进行匹配:
filtObj = {'year':2002,'wheel':15}
m = (df[list(filtObj)] == pd.Series(filtObj)).all(axis=1)
updateObj = {'year':2020}
df.update(pd.DataFrame(updateObj, index=df.index[m]))
print (df)
year wheel
car
audi 2001.0 4
honda 2020.0 15
tesla 2003.0 5
因此需要
dfMatched=df.loc[(df[list(filtObj)]==pd.Series(filtObj)).all(axis=1)].copy()
然后dfMatched.update(pd.DataFrame(updateObj,index=dfMatched.index))
?@jezrael谢谢,但我需要在原始数据框架中更新更改,所以需要dfMatched=df.loc[(df[list(filtObj)]==pd.Series(filtObj))。所有(axis=1)].copy()
然后dfMatched.update(pd.DataFrame(updateObj,index=dfMatched.index))
?@jezrael谢谢,但我需要在原始数据框中更新更改