英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论