Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在满足Column1条件的情况下,用字典键替换Column2值_Python_Pandas_Numpy - Fatal编程技术网

Python 在满足Column1条件的情况下,用字典键替换Column2值

Python 在满足Column1条件的情况下,用字典键替换Column2值,python,pandas,numpy,Python,Pandas,Numpy,我有一本字典,把数字标签和分类标签联系起来 dict = { 0:'cat', 1:'dog', 2:'fish } 我的数据帧(df)输出如下所示: Feature | Feature Value | Feature1 | Feature1 Value Pet 1 Thing 1 Person Steve Pet 1 Place Texas Place

我有一本字典,把数字标签和分类标签联系起来

dict = {
0:'cat',
1:'dog', 
2:'fish
}
我的数据帧(df)输出如下所示:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        1               Thing       1
Person     Steve           Pet         1
Place      Texas           Place       Virginia
我想用“狗”来代替“1”

我试过这个

df.replace({df.loc[df['Feature'] == 'Pet']: dict})
但是,我知道这只是查看匹配特征列,而不是从特征值中提取要在字典中匹配的值

我的数据帧(df)输出应该是:

Feature  | Feature Value | Feature1 |  Feature1 Value

Pet        dog             Thing       1
Person     Steve           Pet         dog
Place      Texas           Place       Virginia

考虑到您的情况,您可以这样做:

df['Feature Value'].map(dict).fillna(df['Feature Value'])

这是非穷举映射,
map()。另外,
map()
repalce()快得多

考虑到您的情况,您可以这样做:

df['Feature Value'].map(dict).fillna(df['Feature Value'])

这是非穷举映射,
map()。另外,
map()
repalce()

快得多。您可以基于特征替换单个特征集/特征值的值

注意:由于Feature_Value列是object type,所以我将其用作所选值的type(int)

df.loc[df['Feature'] == 'Pet', 'Feature_Value']= df.loc[df['Feature'] == 'Pet', 'Feature_Value'].astype(int).replace(d)

df.loc[df['Feature1'] == 'Pet', 'Feature1_Value']= df.loc[df['Feature1'] == 'Pet', 'Feature1_Value'].astype(int).replace(d)


    Feature Feature_Value   Feature1    Feature1_Value
0   Pet     dog             Thing       1
1   Person  Steve           Pet         dog
2   Place   Texas           Place       Virginia

可以基于特征替换单个特征集/特征值的值

注意:由于Feature_Value列是object type,所以我将其用作所选值的type(int)

df.loc[df['Feature'] == 'Pet', 'Feature_Value']= df.loc[df['Feature'] == 'Pet', 'Feature_Value'].astype(int).replace(d)

df.loc[df['Feature1'] == 'Pet', 'Feature1_Value']= df.loc[df['Feature1'] == 'Pet', 'Feature1_Value'].astype(int).replace(d)


    Feature Feature_Value   Feature1    Feature1_Value
0   Pet     dog             Thing       1
1   Person  Steve           Pet         dog
2   Place   Texas           Place       Virginia