【发布时间】:2016-09-16 08:28:12
【问题描述】:
这是我的熊猫数据框。
new_data =
name duration01 duration02 orz01 orz02
ABC 1 years 6 months 5 months Nan Google
XYZ 4 months 3 years 2 months Google Zensar
TYZ 4 months 4 years Google In Google
OPI 2 months 3 months Nan accenture
NRM 9 months 3 years Google Zensar
我想找出在 Google 工作的员工的姓名以及工作时间(以月为单位)。这里的值包含在多个列中吗?如何在多列上应用过滤器?
duration01 => orz01(员工在 orz01 中花费的月/年) duration02 => orz02(员工在 orz02 中花费的月/年)
共有 10 个 orz 和 10 个相应的持续时间列。
我试过下面的代码
# Selected the required columns
orz_cols = new_data.columns[new_data.columns.str.contains('orz')]
new_data [ new_data[orz_cols].apply(lambda x: x.str.contains('Google')) ]
但它没有打印正确的数据?
我是怎么做到的
我想要像下面这样的输出
name Total_duration_in Google_in_Months
ABC 5 months
XYZ 4 months
TYZ 52 months
使用@Stefan 给出的第一部分我在下面所做的将年转换为月
# filter the data
Google_Data = dt1[dt1['orz'].str.contains('Google')]
dur = []
for i in range(0,len(Google_Data['duration'])):
dur.append(Google_Data['duration'][i].split())
months_list = []
for i in range(0,len(dur)):
#print dur[i]
if dur[i][1] == 'years':
if len(dur[i]) > 2:
val1 = int(dur[i][0]) * 12 + int(dur[i][2])
val11 = str(val1)+" months"
months_list.append(val11)
else:
val2 = int(dur[i][0]) * 12
val22 = str(val2)+" months"
months_list.append(val22)
else:
val3 = dur[i][0]+" months"
months_list.append(val3)
months_list[:3]
# Concat
df2 = pd.DataFrame(months_list,index=Google_Data.index.copy())
Google_duration = pd.concat([Google_Data, df2], axis=1)
Output :
organization Duration_In_Months
name
Aparna Arora Google Headstrong Capital Markets 60 months
Aparna Dasgupta Google 24 months
Aparna Dhar Google India Ltd 56 months
现在我想执行最后一步,即通过对名称进行分组来求和,但这里的“名称”是索引。我很难得到总和。
这是我正在尝试的
# Splitting the Duration_In_Months to get only number values
# Its returning the type as 'str'
Google_duration1 = Google_duration.Duration_In_Months.apply(lambda x : x.split()[0])
# apply groupby
Genpact_dur2.index.groupby(Genpact_dur2['Duration_In_Months'])
我如何 Groupby 索引并取总和?
谢谢,
【问题讨论】:
标签: python pandas filter group-by multiple-columns