python 变量列判断后添加列

题目描述

python 变量列判断后添加列
python初学者遇到的问题,希望大佬别嫌弃。
就是先确定日期列的星期几,然后在对应的星期几列查找有没有标注1,如果有结合type列是accomplished的,返回新列标注1,否则标注0。

题目来源及自己的思路

我是现在最后增加一列先写了日期的星期几,然后普通的两个固定列内数据对比写新列我是知道的,变量列就找不到方案了,特来求助。感谢!

相关代码

import pandas as pd

data = {'my_city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'],'my_dates': ['2016-10-1','2016-9-1','2015-10-1','2017-11-1','2016-04-1', '2016-10-1'],'type': ['accomplished', 'accomplished', 'failed', 'accomplished','failed', 'accomplished'],'Monday': ['1','1','1','1','1', '1'],'Tuesday': ['1','1','1','1','1', '1'],'Wedsday': ['1','1','1','1','1', '1'],'Thursday': ['','','','','', ''],'Friday': ['1','1','1','1','1', '1'],'Satday': ['1','1','1','1','1', '1'],'Sunday': ['1','1','1','1','1', '1'],}
df = pd.DataFrame(data)
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek
days = {0:'Monday',1:'Tuesday',2:'Wedsday',3:'Thursday',4:'Friday',5:'Satday',6:'Sunday'}
df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])
df.head(10)

题目补充说明

image.png
第一行2016-10-1是Satday,则到Satday列第一行查找有无1,如果有1且type列是accomplished则新增列写1,否则写0。后续每列如此

阅读 1.6k
1 个回答
新手上路,请多包涵

已解决:

import pandas as pd

def get_weekday(d):
    return d.weekday()

def check(v):
    return 0 if v=='' else 1

data = {'my_city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'],'my_dates': ['2016-10-1','2016-9-1','2015-10-1','2017-11-1','2016-04-1', '2016-10-1'],'type': ['accomplished', 'accomplished', 'failed', 'accomplished','failed', 'accomplished'],'Monday': ['1','1','1','1','1', '1'],'Tuesday': ['1','1','1','1','1', '1'],'Wedsday': ['1','1','1','1','1', '1'],'Thursday': ['','','','','', ''],'Friday': ['1','1','1','1','1', '1'],'Satday': ['1','1','1','1','1', '1'],'Suniday': ['1','1','1','1','1', '1'],}
df = pd.DataFrame(data)
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek
days = {0:'Monday',1:'Tuesday',2:'Wedsday',3:'Thursday',4:'Friday',5:'Satday',6:'Sunday'}

list_1=[  check(df[days[ get_weekday(df['my_dates'][x]) ]][x] )     for x in df.index]
df['标记']=list_1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏