如何在pandas中搜索值的元组?

2024-10-04 09:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数来交换pandas数据帧中目标字典的结果。我想匹配一组值并交换出新值。我试着跟着那排,但我没选。我觉得我错过了一些关键的功能。在

import pandas
testData=pandas.DataFrame([["Cats","Parrots","Sandstone"],["Dogs","Cockatiels","Marble"]],columns=["Mammals","Birds","Rocks"])
target=("Mammals","Birds")
swapVals={("Cats","Parrots"):("Rats","Canaries")}
for x in swapVals:
    #Attempt 1:
    #testData.loc[x,target]=swapVals[x]
    #Attempt 2:
    testData[testData.loc[:,target]==x,target]=swapVals[x]

Tags: 数据函数target目标pandas字典loc关键
1条回答
网友
1楼 · 发布于 2024-10-04 09:25:03

这是用Python2编写的,但是基本思想应该对您有用。它使用应用功能:

import pandas
testData=pandas.DataFrame([["Cats","Parrots","Sandstone"],["Dogs","Cockatiels","Marble"]],columns=["Mammals","Birds","Rocks"])
swapVals={("Cats","Parrots"):("Rats","Canaries")}
target=["Mammals","Birds"]

def swapper(in_row):
    temp =tuple(in_row.values)
    if temp in swapVals:
        return list(swapVals[temp])
    else:
        return in_row

testData[target] = testData[target].apply(swapper, axis=1)

testData

请注意,如果将其他键加载到dict中,则可以在不使用swapper函数的情况下执行apply:

^{pr2}$

相关问题 更多 >