【问题标题】:How to efficiently apply tuple to multiple columns in a pandas dataframe simultaneously如何有效地将元组同时应用于熊猫数据框中的多个列
【发布时间】:2017-10-31 09:10:30
【问题描述】:

我可以得到这个工作

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

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

【问题讨论】:

  • 您能发布一个小的可重现样本数据集和所需的数据集吗? df.apply(..., axis=1) 非常慢。因此,如果我们可以看到您的输入样本数据集和所需的数据集,我们可以尝试找到一个快速的矢量化解决方案......
  • @MaxU 可以不用df.apply 随意做,唯一的要求是我的函数getaTuple() 读取一列并返回两个值,我需要将它们设置为同一数据框中的另外两列。
  • 如果我有一个样本数据集可供使用,并且有一个所需的数据集来检查解决方案是否正确,我会这样做。请阅读how to make good reproducible pandas examples并相应地编辑您的帖子。
  • @MaxU 感谢教程链接,我添加了一个输入/输出示例,如果还有其他问题请告诉我。

标签: python pandas


【解决方案1】:

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

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

【讨论】:

  • 非常优雅,优点是不用碰给定的函数getTuple()
【解决方案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

更新:

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 如果您想要的数据集看起来不同,请将其发布在您的问题中

【讨论】:

  • 太棒了,会试试这个,感谢您建议替代申请
  • @Watt,很高兴我能帮上忙。一旦我们可以看到您的样本数据和所需的数据集,我们就可以提供更精确和经过测试的答案;-)
  • 谢谢,快速提问:如果Col_X 为空或某些行没有_,这仍然有效吗?我能够在getaTuple() 中处理这些边缘情况,想知道您是否可以展示如何以矢量化形式处理?
  • @Watt,我们需要知道所需的数据集(包括边缘情况)应该是什么样子
猜你喜欢
  • 2021-10-06
  • 2013-08-09
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 2017-10-11
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多