gpt4 book ai didi

python - 定义适用于多个数据帧的运算符

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:31 24 4
gpt4 key购买 nike

假设我有两个数据帧:pd1pd2

pd1 = 
A B C
1 hello foo hello
2 foo bar hello
3 world bar world
4 world bar world

pd2 = 

A B C
1 8 0 3
2 8 5 2
3 4 7 0
4 4 1 3

并说我想做一些事情,比如创建具有以下结果的第三个数据框

       A         B      C
1 hello;8 foo;0 hello;3
2 foo;8 bar;5 hello;2
3 world;4 bar;7 world;2
4 world;4 bar;1 world;0

虽然我可以遍历每个位置、索引两个数据帧并将结果连接到第三个数据帧,但我想知道我是否可以做得更好。

正在阅读 applymap我想知道是否有类似的方法来定义和应用适用于成对数据帧的运算符。例如,对于上面的问题,我可以定义以下运算符:

def f(x,y):    
return str(x) + ';' + str(y)

其中 f(x,y) 是一个按元素操作的函数。

这个想法可以扩展到多个数据帧(超过 2 个)。 Pandas 中是否有任何支持定义此类多数据帧运算符的内容?

最佳答案

你已经可以做到这一点,只需使用 applymap 进行字符串化; '+' 连接

In [14]: df1.applymap(str) + df2.applymap(lambda x: ';%s' % x)
Out[14]:
A
0 0;0
1 1;2
2 2;4
3 3;6
4 4;8

可能不是很有效,也许你应该只创建你想要的列,然后用 ';' 的 sep 来创建 to_csv?

关于python - 定义适用于多个数据帧的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15982536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com