Bruno Cazzaniga
Bruno Cazzaniga

Reputation: 23

Create a new pandas dataframe column based on other column of the dataframe

I have a Dataframe that consists in 2 columns:

    String              Is Isogram
0   [47, 0, 49, 12, 46] 1
1   [43, 50, 22, 1, 13] 1
2   [10, 1, 24, 22, 16] 1
3   [2, 24, 3, 24, 51]  0
4   [40, 1, 41, 18, 3]  1

I would like to create another column, with the value 'Is Isogram' appended in the 'String' array, something like this:

    String              Is Isogram  IsoString
0   [47, 0, 49, 12, 46] 1           [47, 0, 49, 12, 46, 1]
1   [43, 50, 22, 1, 13] 1           [43, 50, 22, 1, 13, 1]
2   [10, 1, 24, 22, 16] 1           [10, 1, 24, 22, 16, 1]
3   [2, 24, 3, 24, 51]  0           [2, 24, 3, 24, 51, 0]
4   [40, 1, 41, 18, 3]  1           [40, 1, 41, 18, 3, 1]

I've tried using the apply function with a lambda:

df[''IsoString] = df.apply(lambda x: np.append(x['String'].values, x['Is Isogram'].values, axis=1))

But it throws me a KeyError that i don't really understand

KeyError: ('String', 'occurred at index String')

How can i takle this problem?

Upvotes: 2

Views: 59

Answers (1)

jezrael
jezrael

Reputation: 862431

There is problem axis=1 is called for np.append instead .apply function:

df['IsoString'] = df.apply(lambda x: np.append(x['String'], x['Is Isogram']), axis=1)

Better/faster is use numpy.hstack if same length of each lists in String:

arr = np.hstack((np.array(df['String'].tolist()), df['Is Isogram'].values[:, None]))
print (arr)
[[47  0 49 12 46  1]
 [43 50 22  1 13  1]
 [10  1 24 22 16  1]
 [ 2 24  3 24 51  0]
 [40  1 41 18  3  1]]

df['IsoString'] = arr.tolist()
print (df)
                String  Is Isogram               IsoString
0  [47, 0, 49, 12, 46]           1  [47, 0, 49, 12, 46, 1]
1  [43, 50, 22, 1, 13]           1  [43, 50, 22, 1, 13, 1]
2  [10, 1, 24, 22, 16]           1  [10, 1, 24, 22, 16, 1]
3   [2, 24, 3, 24, 51]           0   [2, 24, 3, 24, 51, 0]
4   [40, 1, 41, 18, 3]           1   [40, 1, 41, 18, 3, 1]

Upvotes: 3

Related Questions