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)

题目补充说明

python 变量列判断后添加列
第一行2016-10-1是Satday,则到Satday列第一行查找有无1,如果有1且type列是accomplished则新增列写1,否则写0。后续每列如此


回答:

已解决:

python">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

以上是 python 变量列判断后添加列 的全部内容, 来源链接: utcz.com/p/938118.html

回到顶部