如何同时在Polars数据框中转换多列?

huangapple go评论57阅读模式
英文:

How do I transform multiple columns simultaneously in polars dataframe?

问题

我有两个数据框,其中一个只有一行,我想以某种方式将第一个数据框中的每一列与单行中的值进行转换。我该如何做到这一点?以下是我想要实现的内容:

df1 = pl.DataFrame({'c1': [2, 4, 6], 'c2': [20, 40, 60], 'c3': [10, 20, 30]})
df2 = pl.DataFrame({'c1': [2], 'c2': [20], 'c3': [10]})
df = df.select([
    pl.col('c1') / df2['c1'],
    pl.col('c2') / df2['c2'],
    pl.col('c3') / df2['c3'],
])

现在,想象一下我有数百列。上面的代码不适用于大规模操作,有什么更好的方法吗?谢谢!

英文:

I have two dataframes, one of them is just a single row, and I would like to transform each of the columns in the first one with the values in the single row in some fashion. How do I do this? Here's what I want to achieve:

df1 = pl.DataFrame({'c1': [2,4,6],'c2': [20,40,60],'c3': [10,20,30]})
df2 = pl.DataFrame({'c1': [2],'c2': [20],'c3': [10]})
df = df.select([
    pl.col('c1')/df2['c1'],
    pl.col('c2')/df2['c2'],
    pl.col('c3')/df2['c3'],
])

Now, imagine I have hundreds of columns. Above code doesn't scale, how do I do this best? Thanks!

答案1

得分: 1

如果 df2 保证是单行,并且 df1 和 df2 的列名始终匹配,那么你可以执行以下操作:

df1.select(pl.col(x)/df2[x] for x in df1.columns)

如果 df2 不止一行,或者 df1 中的列名在 df2 中不存在,那么这将引发错误。

英文:

If df2 is guaranteed to be a single row AND the names from df1 and df2 will always match then you can do:

df1.select(pl.col(x)/df2[x] for x in df1.columns)

If df2 is more than a single row or if the name in df1 don't exist in df2 then this will error out.

huangapple
  • 本文由 发表于 2023年6月12日 22:58:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定