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'
和chainastype(int)
或整数repr
df['c'] = df['b'].eq('yes').groupby(df['a']).transform('any').view('i1')
print(df)
IIUC,您可以在条件序列上使用with after分组,该条件序列检查df['b']
'yes'
和chainastype(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