0
votes

I would like to create a new column 'column_new' based on values from column_1 and column_2 or column_3. If column_1 == 'C', then column_new is same value as column_2, but if column_1 == 'G', then column_new is same value as column_3.

I have tried:

def new_value(x):
   if df1['column_1'] == 'C' :
      return df1['column_2']
   if df1['column_1'] == 'G':
      return df1['column_3']
   else:
       return 'Other'

df1['column_new'] = df1['column_1'].apply(new_value)

error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Have also tried:

for row in df1:
    if df1.loc[df1['column_1'] == 'C']:
        df1['column_new'] = df1['column_2']
    elif df1.loc[df1['column_1'] == 'G']:
        df1['column_new'] = df1['column_3']

error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Some data:

column_1    column_2    column_3
C   AAAACCCACCT ACCCA
C   GTGGGCTAAAA GGCTA
G   ATGGGCTTTTT GGCTT
G   AGAAAGCCCGC AAGCC
3
I have done: df1['column_1'] = df1['column_1'].apply(str)Kristin

3 Answers

2
votes

Try np.select

cond_1 = df['column_1'] == 'C'
cond_2 = df['column_1'] == 'G'
df['column_new'] = np.select([cond_1, cond_2], [df.column_2, df.column_3], 'Other')

Out[1715]:
  column_1     column_2 column_3   column_new
0        C  AAAACCCACCT    ACCCA  AAAACCCACCT
1        C  GTGGGCTAAAA    GGCTA  GTGGGCTAAAA
2        G  ATGGGCTTTTT    GGCTT        GGCTT
3        G  AGAAAGCCCGC    AAGCC        AAGCC
1
votes

Figured it out:

def new_value(column_1,column_2, column_3):
    if column_1 == 'C':
        return column_2[:]
    elif column_1 == 'G':
        return column_3[:]
    else:
        return 'NaN'

df1['column_new'] = df1.apply(lambda row: new_value(row.column_1, row.column_2, row.column_3), axis = 1)
0
votes

You can try: Hope it will work

df['col_new']=df[(df['col2'][df['col1']=='C']) & (df['col3'][df['col1']=='G'])