简体   繁体   English

基于数据框的其他列创建一个新的熊猫数据框列

[英]Create a new pandas dataframe column based on other column of the dataframe

I have a Dataframe that consists in 2 columns:我有一个包含 2 列的数据框:

  • 'String' -> numpy array like [47, 0, 49, 12, 46] 'String' -> numpy 数组,如 [47, 0, 49, 12, 46]

  • 'Is Isogram' -> 1 or 0 “是等值线图”-> 1 或 0

    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',如下所示:

    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:我已经尝试使用带有 lambda 的 apply 函数:

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

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

How can i takle this problem?我该如何解决这个问题?

There is problem axis=1 is called for np.append instead .apply function:有问题axis=1被调用np.append而不是.apply函数:

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 :如果String中每个列表的长度相同,则使用numpy.hstack更好/更快:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM