2017-08-14 183 views
2

我有一個dafatframe像這樣的內容:蟒蛇大熊貓 - 列變化值布爾基於另一列

A  B 
0 NaN string1 
1 NaN string2 
2 Nan string1 
3 Nan string1 

我如何更改列所有值使得它們基於布爾列B中同一索引處的條目是否包含某個字符串「stringX」?

+1

在這種情況下,如果stringX =「string1」,那麼列A中的所需輸出爲真假False True True –

+0

謝謝jezrael! –

+0

不客氣! – jezrael

回答

3

我想你需要指定布爾面具,而不是==可以使用eq或使用assign

#if need True False values by condition 
stringX = "string1" 
df['A'] = df['B'] == stringX 
print (df) 
     A  B 
0 True string1 
1 False string2 
2 True string1 
3 True string1 

df['A'] = df['B'].eq(stringX) 
print (df) 
     A  B 
0 True string1 
1 False string2 
2 True string1 
3 True string1 

df = df.assign(A=df['B'].eq(stringX)) 
print (df) 
     A  B 
0 True string1 
1 False string2 
2 True string1 
3 True string1 

#if need values of column by condition 
df.loc[df['B'] == 'string1', 'A'] = df['B'] 
print (df) 
     A  B 
0 string1 string1 
1  NaN string2 
2 string1 string1 
3 string1 string1 

#if need scalar by condition 
df.loc[df['B'] == 'string1', 'A'] = 1 
print (df) 
    A  B 
0 1 string1 
1 NaN string2 
2 1 string1 
3 1 string1 

#if need if else condition with 2 scalars 
df['A'] = np.where(df['B'] == 'string1', 1, 2) 
print (df) 
    A  B 
0 1 string1 
1 2 string2 
2 1 string1 
3 1 string1