gpt4 book ai didi

python - 将多个 DataFrame 列压缩为 Pandas 中的单个指示器列

转载 作者:行者123 更新时间:2023-12-05 09:06:07 25 4
gpt4 key购买 nike

假设我有一个如下所示的 DataFrame:

import pandas as pd
import numpy as np

d = {'ID': [1,2,3,4],
'name': ['bob','shelby','jordan','jeff'],
'type1': [1,1,0,0],
'type2':[1,0,1,0],
'type4':[1,0,0,0],
'type5':[0,0,1,0],
'type6':[0,1,0,0],
'type8':[0,0,1,0]}
df: pd.DataFrame = pd.DataFrame(data=d)
print(df.head(9))

ID name type1 type2 type4 type5 type6 type8
0 1 bob 1 1 1 0 0 0
1 2 shelby 1 0 0 0 1 0
2 3 jordan 0 1 0 1 0 1
3 4 jeff 0 0 0 0 0 0

我想将“type5”、“type6”和“type8”列压缩到一个名为“other”的列中,并将任何“1”指示符聚合为新的“other”列中的“1”。因此,如果“jordan”有一个“其他”列条目,他应该有一个“1”指示符,因为他在 type6 和 type8 中有一个“1”(因此对每个选定列(type5,type6)在行中使用 max() 操作, 类型 8)

所需的框架应该是这样的:

   ID    name  type1  type2  type4  other 
0 1 bob 1 1 1 0
1 2 shelby 1 0 0 1
2 3 jordan 0 1 0 1
3 4 jeff 0 0 0 0

我需要为要压缩的列创建一个 bool 掩码,然后在它们之间聚合以创建新列,同时删除旧列。我怎么能这样做?

最佳答案

在这里试试你的逻辑

drop_cols = ['type5','type6','type8']

df = (df.assign(other=df[drop_cols].max(1)) # new column with max value
.drop(columns=drop_cols) # drop the old columns
)

输出:

   ID    name  type1  type2  type4  other
0 1 bob 1 1 1 0
1 2 shelby 1 0 0 1
2 3 jordan 0 1 0 1
3 4 jeff 0 0 0 0

关于python - 将多个 DataFrame 列压缩为 Pandas 中的单个指示器列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66336771/

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