python - 如果值是第一次出现并且最近一年出现在 Pandas 中,如何创建 0 或 1

标签 python python-3.x pandas dataframe

我有一个数据框,我需要根据新出现的列值创建包含 0 和 1 的新列。

数据框输入:

df = pd.DataFrame({'value_text': ['type1', 'type1', 'type1','type2','type2','type3','type3','type4','type4','type5','type6'],
                   'year': [2016,2017,2021,2018,2021,2019,2021,2020,2021,2021,2021]})


     value_text  year
0       type1  2016
1       type1  2017
2       type1  2021
3       type2  2018
4       type2  2021
5       type3  2019
6       type3  2021
7       type4  2020
8       type4  2021
9       type5  2021
10      type6  2021

基于此需要创建包含 0 和 1 的新列,考虑到 value_text 在当年也只出现一次。

这里的result data frame type5只在当年出现过,往年没有出现过。基本上是尝试识别新事件并创造值(value) 1 否则 0。

结果:

df1 = pd.DataFrame({'value_text': ['type1', 'type1', 'type1','type2','type2','type3','type3','type4','type4','type5','type6'],
                   'year': [2016,2017,2021,2018,2021,2019,2021,2020,2021,2021,2021],
                   'value': [0, 0, 0,0,0,0,0,0,0,1,1]})

输出:

     value_text  year  value
0       type1  2016      0
1       type1  2017      0
2       type1  2021      0
3       type2  2018      0
4       type2  2021      0
5       type3  2019      0
6       type3  2021      0
7       type4  2020      0
8       type4  2021      0
9       type5  2021      1
10      type6  2021      1

最佳答案

我们可以使用 duplicated 创建一个 bool 掩码 m1 来识别不重复的值。类似地,通过将​​年份列与当前年份进行比较来创建另一个 bool 掩码 m2,现在采用 m1m2 的逻辑 and 并将结果分配给 value

m1 = ~df['value_text'].duplicated()
m2 = df['year'].eq(pd.Timestamp('now').year)
df['value'] = (m1 & m2).view('i1')

>>> df

   value_text  year  value
0       type1  2016      0
1       type1  2017      0
2       type1  2021      0
3       type2  2018      0
4       type2  2021      0
5       type3  2019      0
6       type3  2021      0
7       type4  2020      0
8       type4  2021      0
9       type5  2021      1
10      type6  2021      1

关于python - 如果值是第一次出现并且最近一年出现在 Pandas 中,如何创建 0 或 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67105439/

相关文章:

python - 没有足够的背景过滤

python - 正则表达式重命名文件夹 Métamorphose

python - 为什么 doctest 没有检测到我的测试?

Python 行继续字符后出现意外字符

python - 如何解决 numpy 中的内存 View 错误?

python - str 包含 datetime64 pandas 的等价物

python - 计算值并在新的数据框列中添加引用

python - 为 LSTM 模型调用预测函数时出现有关输入形状的错误

python - 模块未找到错误 : No module named 'xarray.core.accessors'

python - 根据索引条件从 Pandas DataFrame 中删除行