English 中文(简体)
如何重新排序重复极数据框架的答案
原标题:How to re order duplicates answers on polars dataframe
我有一个包含多个问题和答案的极地数据框。 问题在于每个答案都包含在它自己的栏目中, 这意味着我有很多多余的信息。 因此, 我希望为问题和答案只有一个列。 下面是数据的例子 : 数据 = {“ ID ” : [1, 1, 1, “ 问题 ” : [“ A”, B”, C, “ 问题 ”, “ 问题 A ” : [“ Answer A, “ Answer A”, “ Answer B ” : [ Answer B, “ Answer B”, “ Answer C”, “ Ans” (d) a. (d) af. fre, (d) d. (d) d. (d) a. (d) a. (d) (d) a. (d) (d) (d) a. (d) y. (i) (d) (i) (y. (d) ) (y. a f) a. (d) a f) a f.
最佳回答
TLDR. import polars.selectors as cs ( df .unpivot( on=cs.starts_with("Answer"), index=["ID", "Question"], variable_name="Source", value_name="Answer", ) .filter( pl.col("Question") == pl.col("Source").str.strip_prefix("Answer ") ) .drop("Source") ) shape: (3, 3) ┌─────┬──────────┬───────────────────┐ │ ID ┆ Question ┆ Answer │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪══════════╪═══════════════════╡ │ 1 ┆ A ┆ Some answer │ │ 1 ┆ B ┆ Some other answer │ │ 1 ┆ C ┆ Another answer │ └─────┴──────────┴───────────────────┘ Explanation. An approach that is a bit more general is to melt (pl.DataFrame.unpivot) the dataframe on the answer columns. This gives you a long format dataframe, which for each original row contains one row for each answer column. import polars.selectors as cs ( df .unpivot( on=cs.starts_with("Answer"), index=["ID", "Question"], variable_name="Source", value_name="Answer", ) ) shape: (9, 4) ┌─────┬──────────┬──────────┬───────────────────┐ │ ID ┆ Question ┆ Source ┆ Answer │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ str │ ╞═════╪══════════╪══════════╪═══════════════════╡ │ 1 ┆ A ┆ Answer A ┆ Some answer │ │ 1 ┆ B ┆ Answer A ┆ Some answer │ │ 1 ┆ C ┆ Answer A ┆ Some answer │ │ 1 ┆ A ┆ Answer B ┆ Some other answer │ │ 1 ┆ B ┆ Answer B ┆ Some other answer │ │ 1 ┆ C ┆ Answer B ┆ Some other answer │ │ 1 ┆ A ┆ Answer C ┆ Another answer │ │ 1 ┆ B ┆ Answer C ┆ Another answer │ │ 1 ┆ C ┆ Answer C ┆ Another answer │ └─────┴──────────┴──────────┴───────────────────┘ From here, it is easy to (after some transformation) filter for rows in which the Source column matches the question (see TLDR).
问题回答
If there are a limited number of answer columns, this can be done with a simple pl.when().then() chain: df2 = df.select( "ID", "Question", pl.when(pl.col("Question") == "A") .then("Answer A") .when(pl.col("Question") == "B") .then("Answer B") .when(pl.col("Question") == "C") .then("Answer C") .alias("Answer"), ) This will set the value from the column Answer A as Answer if Question == "A" and so on.
Using functools.reduce you can generalize Dogbert s solution to an arbitrary number of columns: import polars as pl from functools import reduce answer_cols = ["A", "B", "C"] answer = reduce( lambda expr, q: expr.when(Question=q).then(pl.col(f"Answer {q}")), answer_cols, pl.when(False).then(None) # initial expression / dummy condition ) res = df.select("ID", "Question", answer.alias("Answer")) Or if you prefer not to use functools.reduce: answer = pl.when(False).then(None) for q in answer_cols: answer = answer.when(Question=q).then(pl.col(f"Answer {q}")) Note that the initial condition pl.when(False).then(None) is always false, and is only needed to initialize the when-then chain expression Output: >>> res shape: (3, 3) ┌─────┬──────────┬──────────┐ │ ID ┆ Question ┆ Answer │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪══════════╪══════════╡ │ 1 ┆ A ┆ Answer A │ │ 1 ┆ B ┆ Answer B │ │ 1 ┆ C ┆ Answer C │ └─────┴──────────┴──────────┘




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签