簡體   English   中英

根據熊貓的第四列將數據從一列移到另一列中的另一列

[英]Move data from one column to one of two others based on a fourth column in pandas

所以在熊貓我有以下數據框

A B C D
0 X   
1 Y   
0 Y   
1 Y   
0 X
1 X    

我想根據B將A中的值移動到C或D。輸出應該是這樣的;

A B C D
0 X 0 
1 Y   1 
0 Y   0
1 Y   1 
0 X 0
1 X 1  

我試過使用多個where語句,例如

df['C'] = np.where(str(df.B).find('X'), df.A, '')
df['D'] = np.where(str(df.B).find('Y'), df.A, '')

但是結果是:

A B C D
0 X 0 0
1 Y 1 1 
0 Y 0 0
1 Y 1 1 
0 X 0 0
1 X 1 1 

因此,我想它正在檢查該值是否完全存在於該列中,這很有意義。 我需要逐行迭代嗎?

不要使用find轉換為str ,因為它返回標量,並且0轉換為False ,另一個整數轉換為True

print (str(df.B).find('X'))
5

最簡單的是布爾Series比較值:

print (df.B == 'X')
0     True
1    False
2    False
3    False
4     True
5     True
Name: B, dtype: bool

df['C'] = np.where(df.B == 'X', df.A, '')
df['D'] = np.where(df.B == 'Y', df.A, '')

assign +的另一種解決方案, where

df = df.assign(C=df.A.where(df.B == 'X', ''),
               D=df.A.where(df.B == 'Y', ''))

如果需要檢查子字符串,請使用str.contains

df['C'] = np.where(df.B.str.contains('X'), df.A, '')
df['D'] = np.where(df.B.str.contains('Y'), df.A, '')

要么:

df['C'] = df.A.where(df.B.str.contains('X'), '')
df['D'] = df.A.where(df.B.str.contains('Y'), '')

全部返回:

print (df)
   A  B  C  D
0  0  X  0   
1  1  Y     1
2  0  Y     0
3  1  Y     1
4  0  X  0   
5  1  X  1   

使用切片分配

n = len(df)
f, u = pd.factorize(df.B.values)
a = np.empty((n, 2), dtype=object)
a.fill('')
a[np.arange(n), f] = df.A.values

df.loc[:, ['C', 'D']] = a

df

   A  B  C  D
0  0  X  0   
1  1  Y     1
2  0  Y     0
3  1  Y     1
4  0  X  0   
5  1  X  1 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM