python - 如何标记满足某些标准的每个组的第一个条目?
问题描述
假设我有一些数据框,其中一列的某些值多次出现形成组(A
片段中的列)。现在,我想创建一个新列,例如每个组1
的第一个x
(列C
)条目和0
其他条目。我设法完成了第一部分,但是我没有找到在x
es 上包含条件的好方法,有没有好的方法呢?
import pandas as pd
df = pd.DataFrame(
{
"A": ["0", "0", "1", "2", "2", "2"], # data to group by
"B": ["a", "b", "c", "d", "e", "f"], # some other irrelevant data to be preserved
"C": ["y", "x", "y", "x", "y", "x"], # only consider the 'x'
}
)
target = pd.DataFrame(
{
"A": ["0", "0", "1", "2", "2", "2"],
"B": ["a", "b", "c", "d", "e", "f"],
"C": ["y", "x", "y", "x", "y", "x"],
"D": [ 0, 1, 0, 1, 0, 0] # first entry per group of 'A' that has an 'C' == 'x'
}
)
# following partial solution doesn't account for filtering by 'x' in 'C'
df['D'] = df.groupby('A')['C'].transform(lambda x: [1 if i == 0 else 0 for i in range(len(x))])
解决方案
在你的情况下,然后切片drop_duplicates
并分配回来
df['D'] = df.loc[df.C=='x'].drop_duplicates('A').assign(D=1)['D']
df['D'].fillna(0,inplace=True)
df
Out[149]:
A B C D
0 0 a y 0.0
1 0 b x 1.0
2 1 c y 0.0
3 2 d x 1.0
4 2 e y 0.0
5 2 f x 0.0
推荐阅读
- html - 我们能看到引导类中的代码吗?
- java - 结果集需要很长时间来处理来自 Oracle 的大数据
- r - 如何循环遍历数据矩阵并在选定行上进行计算?
- django - Django - 创建一个清单表单
- javascript - 使用 immer 不能修改属性 Number of nested object
- javascript - 在 componentDidMount() 中反应 Axios 调用
- reactjs - 将 Vue 插槽代码转换为 React 插槽代码 - 传递数据时遇到问题
- windows - 无法使用远程容器将 C/C++ 扩展安装到 VisualCode
- ios - 在 App Store Connect 上找不到编辑版本。尝试使用'--use_live_version true'
- magento - Magento 2.3.3 数据库 ERD