如何有效地将元组同时应用于pandas数据帧中的多个列

2024-05-02 08:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以让它工作

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

当我的函数返回元组时

^{pr2}$

但是,我需要知道是否有一种方法可以使用一个函数调用将元组输出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

仅供参考,这类似于how to apply a function to multiple columns in a pandas dataframe at one time 但不是重复的,因为我需要将col_X作为输入传递给函数。在


Tags: columnsto方法lambda函数dfstringcol
2条回答

以下是矢量化解决方案:

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

更新:

^{pr2}$

PS如果你想要的数据集看起来不一样,请把它贴在你的问题上

如果我没弄错你的问题,这应该行得通:

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

相关问题 更多 >