【发布时间】:2017-01-20 08:50:27
【问题描述】:
我有 2 个数据帧,df1 和 df2,并且想要执行以下操作,将结果存储在 df3:
for each row in df1:
for each row in df2:
create a new row in df3 (called "df1-1, df2-1" or whatever) to store results
for each cell(column) in df1:
for the cell in df2 whose column name is the same as for the cell in df1:
compare the cells (using some comparing function func(a,b) ) and,
depending on the result of the comparison, write result into the
appropriate column of the "df1-1, df2-1" row of df3)
例如:
df1
A B C D
foo bar foobar 7
gee whiz herp 10
df2
A B C D
zoo car foobar 8
df3
df1-df2 A B C D
foo-zoo func(foo,zoo) func(bar,car) func(foobar,foobar) func(7,8)
gee-zoo func(gee,zoo) func(whiz,car) func(herp,foobar) func(10,8)
我从这个开始:
for r1 in df1.iterrows():
for r2 in df2.iterrows():
for c1 in r1:
for c2 in r2:
但我不确定如何处理它,希望能得到一些帮助。
【问题讨论】:
-
因为您正在将 func 应用于同名列,所以您可以仅遍历列并使用矢量化,例如df3['A'] = func(df1['A'], df2['A']) 等等?
-
@StarFox 很有趣,所以我可以这样做:对于 df3 中的列:df3[column] = func(df1[column], df2[column])?
-
当然!这就是 pandas/numpy 的力量(通常是矢量化)。我将在下面提供一些示例,我们将从那里开始
-
我认为你可以在你的 2 个数据帧之间的笛卡尔积上建立一个解决方案,看看这里作为一个起点:stackoverflow.com/questions/13269890/…
-
@Svend 这似乎是一个很有前途的想法,谢谢!不过,我会先尝试 StarFox 的解决方案。
标签: python pandas dataframe iterator iteration