我应该如何在数据框中最多使用2列并使其成为另一列?

时间:2021-01-02 08:01:10

I have a dataframe with columns A,B. I need to create a column C such that for every record / row:

我有一个包含A,B列的数据框。我需要创建一个C列,以便每个记录/行:

C = max(A, B).

C = max(A,B)。

How should I go about doing this?

我该怎么做呢?

Thanks.

1 个解决方案

#1


64  

You can get the maximum like this:

你可以得到这样的最大值:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

如果您知道“A”和“B”是唯一的列,您甚至可以逃脱

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

我猜你也可以使用.apply(max,axis = 1)。

#1


64  

You can get the maximum like this:

你可以得到这样的最大值:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

如果您知道“A”和“B”是唯一的列,您甚至可以逃脱

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

我猜你也可以使用.apply(max,axis = 1)。