将功能应用于熊猫数据框中的特定选定列

时间:2019-11-28 06:17:42

标签: pandas pandas-apply

我有以下数据框:

# List of Tuples
matrix = [([22, 23], [34, 35, 65], [23, 29, 31]),
         ([33, 34], [31, 44], [11, 16, 18]),
         ([44, 56, 76], [16, 34, 76], [21, 34]),
         ([55, 34], [32, 35, 38], [22, 24, 26]),
         ([66, 65, 67], [33, 38, 39], [27, 32, 34]),
         ([77, 39, 45], [35, 36, 38], [11, 21, 34])]

# Create a DataFrame object
df = pd.DataFrame(matrix, columns=list('xyz'), index=list('abcdef'))

enter image description here

我可以将自定义函数应用于以下列表中所有列的开始,结束项目:

def fl(x):
    return [x[0], x[len(x)-1]]

df.apply(lambda x : [fl(i) for i in x])

enter image description here

但是我想将该功能应用于选定的x和z列。

我正在尝试像下面这样引用此link

df.apply(lambda x: fl(x) if x in ['x', 'y'] else x)

并这样:

df[['x', 'y']].apply(fl)

如何在不更改y列的情况下仅将函数应用于x和z列来获取输出。

2 个答案:

答案 0 :(得分:1)

使用DataFrame.applymap进行元素处理,也可以使用[-1]索引来获取最后一个值:

def fl(x):
    return [x[0], x[-1]]

df[['x', 'z']] = df[['x', 'z']].applymap(fl) 
print (df)
          x             y         z
a  [22, 23]  [34, 35, 65]  [23, 31]
b  [33, 34]      [31, 44]  [11, 18]
c  [44, 76]  [16, 34, 76]  [21, 34]
d  [55, 34]  [32, 35, 38]  [22, 26]
e  [66, 67]  [33, 38, 39]  [27, 34]
f  [77, 45]  [35, 36, 38]  [11, 34]

或者对于使用DataFrame.apply的解决方案,请使用zip将元组映射到list并通过str进行selexing:

def fl(x):
    return list(map(list, zip(x.str[0], x.str[-1])))

df[['x', 'z']] = df[['x', 'z']].apply(fl) 
print (df)
          x             y         z
a  [22, 23]  [34, 35, 65]  [23, 31]
b  [33, 34]      [31, 44]  [11, 18]
c  [44, 76]  [16, 34, 76]  [21, 34]
d  [55, 34]  [32, 35, 38]  [22, 26]
e  [66, 67]  [33, 38, 39]  [27, 34]
f  [77, 45]  [35, 36, 38]  [11, 34]

答案 1 :(得分:0)

发现我正在做的错误。

感谢您的答复。

我更改了如下功能:

def fl(x):
    new = []
    for i in x:
        new.append([i[0], i[-1]])
    return new

然后应用了这样的功能。

df.apply(lambda x : fl(x) if x.name in ['x', 'z'] else x)

那我就能得到预期的输出。