Python 将值映射到行等于列标题的列-行
我试图在一个使用特定行值的文件中创建一个新的列标题。使用下面的命令,对于Python 将值映射到行等于列标题的列-行,python,pandas,Python,Pandas,我试图在一个使用特定行值的文件中创建一个新的列标题。使用下面的命令,对于组中的每一行,我想映射蓝色的红色中的相应值 import pandas as pd import numpy as np df = pd.DataFrame({ 'Time' : [1,1,1,1,1,1], 'Red' : ['1','1','1','4','4','4'], 'Blue' : ['3','
组
中的每一行,我想映射蓝色
的红色
中的相应值
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Time' : [1,1,1,1,1,1],
'Red' : ['1','1','1','4','4','4'],
'Blue' : ['3','3','3','5','5','5'],
'Group' : ['Red','Blue','Red','Blue','Red','Blue',],
'Output' : ['1','3','1','5','4','5',],
})
df['Output'] = np.where(df['Group'] == df['Red'], df['Red'], df['Blue'])
预期产出:
Time Red Blue Group Output
0 1 1 3 Red 1
1 1 1 3 Blue 3
2 1 1 3 Red 1
3 1 4 5 Blue 5
4 1 4 5 Red 4
5 1 4 5 Blue 5
而不是做:
df['Output'] = np.where(df['Group'] == df['Red'], df['Red'], df['Blue'])
#you are making mistake here ^ ^
做:
df的输出
:
Time Red Blue Group Output
0 1 1 3 Red 1
1 1 1 3 Blue 3
2 1 1 3 Red 1
3 1 4 5 Blue 5
4 1 4 5 Red 4
5 1 4 5 Blue 5
Time Red Blue Group Output
0 1 1 3 Red 1
1 1 1 3 Blue 3
2 1 1 3 Red 1
3 1 4 5 Blue 5
4 1 4 5 Red 4
5 1 4 5 Blue 5