gpt4 book ai didi

python - 使用列表根据多列中的值有条件地填充新列

转载 作者:行者123 更新时间:2023-12-01 03:38:04 25 4
gpt4 key购买 nike

我正在尝试使用多个列中的值来填充 pandas 数据框中的新列。原始列为 0 或“1”,每个系列只有一个 1。通过填充 new_col = [1, 3, 7, 10],新列将对应于 df['A','B','C','D'],如下所示。 (A 处的 1 表示 new_col = 1;如果 B=1new_col = 3 等)

df    
A B C D
1 1 0 0 0
2 0 0 1 0
3 0 0 0 1
4 0 1 0 0

新的 df 应该如下所示。

df    
A B C D new_col
1 1 0 0 0 1
2 0 0 1 0 7
3 0 0 0 1 10
4 0 1 0 0 3

我尝试过使用 maplocwhere 但似乎无法制定有效的方法来完成它。问题似乎非常接近to this 。我看过的其他几篇文章1 2 3 。这些都没有展示如何有条件地使用多个列来填充基于列表的新列。

最佳答案

我可以想到几种方法,主要涉及 argmaxidxmax,来获取可用于填充列的 ndarray 或 Series。

我们可以下拉到 numpy,找到最大位置(1 所在的位置)并使用它们来索引 new_col 的数组版本:

In [148]: np.take(new_col,np.argmax(df.values,1))
Out[148]: array([ 1, 7, 10, 3])

我们可以创建一个系列,以 new_col 作为值,以列作为索引,并使用 idxmax 对其进行索引:

In [116]: pd.Series(new_col, index=df.columns).loc[df.idxmax(1)].values
Out[116]: array([ 1, 7, 10, 3])

我们可以使用 get_indexer 将列 idxmax 结果转换为可以与 new_col 一起使用的整数偏移量:

In [117]: np.array(new_col)[df.columns.get_indexer(df.idxmax(axis=1))]
Out[117]: array([ 1, 7, 10, 3])

或者(这看起来非常浪费)我们可以用新列创建一个新框架并直接使用 idxmax:

In [118]: pd.DataFrame(df.values, columns=new_col).idxmax(1)
Out[118]:
0 1
1 7
2 10
3 3
dtype: int64

关于python - 使用列表根据多列中的值有条件地填充新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com