如何同时将元组有效地应用于PANDAS DataFrame中的多个列



我可以得到此工作

df['col_A'] = df.apply(lambda x: getSingleValue(x['col_X']), axis=1)

以及我的功能返回元组时

df['col_A'] = df.apply(lambda x: getaTuple(x['col_X'])[0], axis=1)
df['col_B'] = df.apply(lambda x: getaTuple(x['col_X'])[1], axis=1)

但是,我需要知道是否有一种方法可以使用单个函数调用来将元组输出getaTuple()应用于数据框的多个列,而不是为每列调用getaTuple多次,我正在设置该值。

这是输入和输出的示例

df = pd.DataFrame(["testString_1", "testString_2", "testString_3"], columns=['column_X'])
def getaTuple(string):
    return tuple(string.split("_"))
In [3]: iwantthis
Out[3]: 
   col_X        col_A       col_B
0  testString_1 testString  1
1  testString_2 testString  2
2  testString_3 testString  3

fyi,这类似于如何一次将函数应用于熊猫数据框中的多个列但不像我一样重复,我需要将col_X作为输入传递给我的功能。

如果我正确理解您的问题,这应该有效:

df[['col_A','col_B']] = df['col_X'].apply(getaTuple).apply(pd.Series)

这是矢量化解决方案:

In [53]: df[['col_A','col_B']] = df.column_X.str.split('_', expand=True)
In [54]: df
Out[54]:
       column_X       col_A col_B
0  testString_1  testString     1
1  testString_2  testString     2
2  testString_3  testString     3

更新:

In [62]: df[['col_A','col_B']] = df.column_X.str.split('_', expand=True)
In [63]: df
Out[63]:
       column_X       col_A col_B
0  testString_1  testString     1
1  testString_2  testString     2
2  testString_3  testString     3
3                            None
4       aaaaaaa     aaaaaaa  None

ps如果您所需的数据集应差异不同,请在您的问题中发布

最新更新