Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建具有基于groupby的值的数据帧向量_Python_Pandas_Conditional Statements_Grouping - Fatal编程技术网

Python 如何创建具有基于groupby的值的数据帧向量

Python 如何创建具有基于groupby的值的数据帧向量,python,pandas,conditional-statements,grouping,Python,Pandas,Conditional Statements,Grouping,鉴于以下数据: x1='one' x2=‘二’ x3=‘三’ y1=‘是’ y2=‘否’ n=3 df=pd.数据帧(dict( a=[x1]*n+[x2]*n+[x3]*n, b=[ y1, y1, y2, y2, y2, y2, y2, y2, y1, ] )) 看起来是: Out[5]: a b 0 one yes 1 one yes 2 one no 3 two no 4 two no 5 two no 6

鉴于以下数据:

x1='one'
x2=‘二’
x3=‘三’
y1=‘是’
y2=‘否’
n=3
df=pd.数据帧(dict(
a=[x1]*n+[x2]*n+[x3]*n,
b=[
y1,
y1,
y2,
y2,
y2,
y2,
y2,
y2,
y1,
]
))
看起来是:

Out[5]:
       a    b
0    one  yes
1    one  yes
2    one   no
3    two   no
4    two   no
5    two   no
6  three   no
7  three   no
8  three  yes
我想知道是否可以创建列
c
,如下所示:

Out[5]:
       a    b   c
0    one  yes   1
1    one  yes   1
2    one   no   1
3    two   no   0
4    two   no   0
5    two   no   0
6  three   no   1
7  three   no   1
8  three  yes   1
其中
c
定义为
1
如果
a
中的组
b
列包含
yes

我尝试了以下方法:

group_results = df.groupby('a').apply(lambda x:  'yes' in x.b.to_list() )
group_results = group_results.reset_index()
group_results = group_results.rename(columns = {0 : 'c'})
df = pd.merge(df, group_results, left_on = 'a', 
                  right_on = 'a', 
                  how = 'left').copy()
但我觉得似乎有更好的方法。

IIUC,您可以在条件序列上使用with after分组,检查是否
df['b']
'yes'
和chain
astype(int)
或整数repr

df['c'] = df['b'].eq('yes').groupby(df['a']).transform('any').view('i1')
print(df)

IIUC,您可以在条件序列上使用with after分组,该条件序列检查df['b']
'yes'
和chain
astype(int)
或integer repr

df['c'] = df['b'].eq('yes').groupby(df['a']).transform('any').view('i1')
print(df)

用于在
a
列中至少有一个
yes
的测试组,最后将掩码转换为整数:

详细信息

print(df.loc[df['b'].eq('yes'), 'a'])
0      one
1      one
8    three
Name: a, dtype: obje
用于在
a
列中至少有一个
yes
的测试组,最后将掩码转换为整数:

详细信息

print(df.loc[df['b'].eq('yes'), 'a'])
0      one
1      one
8    three
Name: a, dtype: obje