1 回答

TA贡献1963条经验 获得超6个赞
我认为需要isin有loc:
df1.loc[df1['id'].isin(postData['id']), 'id'] = 'XX'
print (df1)
id B S
0 XX c f
1 XX d g
2 XX e h
3 XX d j
4 XX d e
5 XX c j
6 h s t
7 i e r
8 j s p
9 k q p
如果想要更动态的解决方案 -intersection用于 DataFrame 和字典中的列名称并在循环中设置值:
postStr = """{
"S":["f","h"],
"id":["a","b","c","d","f","g"],
"currencycode":["USD"]
}"""
postData = json.loads(postStr, object_pairs_hook=OrderedDict)
print (postData)
OrderedDict([('S', ['f', 'h']),
('id', ['a', 'b', 'c', 'd', 'f', 'g']),
('currencycode', ['USD'])])
df = {
'id':['a','b','c','d','f','g','h','i','j','k'],
'B':['c','d','e','d','d','c','s','e','s','q'],
'S':['f','g','h','j','e','j','t','r','p','p']
}
df1 = pd.DataFrame(df)
for col in df1.columns.intersection(postData.keys()):
df1.loc[df1[col].isin(postData[col]), col] = 'XX'
print (df1)
id B S
0 XX c XX
1 XX d g
2 XX e XX
3 XX d j
4 XX d e
5 XX c j
6 h s t
7 i e r
8 j s p
9 k q p
没有找到匹配的内容?试试慕课网站内搜索吧
添加回答
举报