2017-05-21 110 views
1

我有一個數據幀是這樣的:Python中,熊貓===>創建新列根據另一列

 nt 
12062 Python Pandas: Create new column out of other columns where value is not null 
12063 Python Pandas Create New Column with Groupby().Sum() 
12064 
12065 Python - Pandas - create 「first fail」 column from other column data 
12066 
12067 
12068 Creating new column in pandas based on value of other column 
12070 Merge with pandas creating new columns? 

我想要得到的是:

創建一個新的如果nt列具有「創建」字,則列(列名稱爲CreateC)的行等於1。事情是這樣的:

 nt                    CreateC 
12062 Python Pandas: Create new column out of other columns where value is not null 1 
12063 Python Pandas Create New Column with Groupby().Sum()       1 
12064                   0 
12065 Python - Pandas - create 「first fail」 column from other column data  1 
12066                   0 
12067                 0 
12068 Creating new column in pandas based on value of other column 0 
12070 Merge with pandas creating new columns?       0 

什麼,我所做的是:

我創建索引的新柱基 然後找到行包括「創建」 然後找到這些行的索引號

df['index1'] = df.index 
dfCreate = df[df['dataframe'].str.contains("Create", na = False)] 
dfCreateIndex = dfCreate.index.tolist() 

def CreateCs (row): 
    RowIndex1 = pd.to_numeric(row['index1'], errors='coerce') 
    for i in dfCreateIndex: 
     y = dfCreateIndex 
     if RowIndex1 == y: 
      return '1' 
     else: 
      return '0' 
df['CreateC'] = df.apply(lambda row: CreateCs(row), axis=1) 

,但我只得到了:

ValueError: ('The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0') 

有沒有簡單的方法來做到這一點?

回答

1

可以使用str.contains布爾面膜,然後用astype轉換TrueFalse10int,然後由另一astype轉換爲str(如有必要):

df['CreateC'] = df['nt'].str.contains('Create', case=False).astype(int).astype(str) 
print (df) 
                 nt CreateC 
12062 Python Pandas: Create new column out of other ...  1 
12063 Python Pandas Create New Column with Groupby()...  1 
12064               0 
12065 Python - Pandas - create 「first fail」 column f...  1 
12066               0 
12067               0 
12068 Creating new column in pandas based on value o...  0 
12070   Merge with pandas creating new columns?  0 

與另一種解決方案numpy.where

df['CreateC'] = np.where(df['nt'].str.contains('Create', case=False), '1', '0') 
print (df) 
                 nt CreateC 
12062 Python Pandas: Create new column out of other ...  1 
12063 Python Pandas Create New Column with Groupby()...  1 
12064               0 
12065 Python - Pandas - create 「first fail」 column f...  1 
12066               0 
12067               0 
12068 Creating new column in pandas based on value o...  0 
12070   Merge with pandas creating new columns?  0 
+0

謝謝你, 第二種解決方案適用於我,我稍微改變了它 'np.where(df ['nt']。str.contains('Create',case = True,na = False,regex = True),' 1','0')' –

+0

我接受它:)再次感謝。 –

+0

謝謝,祝你好運! – jezrael

相關問題