我希望根据一些列的相应类别创建特定于类别的列。在
我以一种迂回的方式实现了这一点:(1)将两个类别分成两个单独的数据帧,(2)合并日期的两个数据帧(3)删除多余的列(4)创建新的列(与类别无关)(4)删除类别特定的列。你知道有没有更有效的方法来完成这个转变?我的代码在示例输入/输出下面
输入:
wk start car rims color Autopilot$ Sunroof$
0 2018-09-09 tesla model x 17 black 3000 0
1 2018-09-16 tesla model x 14 yellow 3000 0
2 2018-09-23 tesla model x 13 white 3000 0
3 2018-09-09 tesla model 3 19 grey 0 2000
4 2018-09-16 tesla model 3 21 pink 0 2000
理想输出:
^{pr2}$我的代码:
import pandas as pd
df = pd.DataFrame({'wk start': ['2018-09-09', '2018-09-16', '2018-09-23','2018-09-09', '2018-09-16'],
'car': [ 'tesla model x', 'tesla model x', 'tesla model x','tesla model 3','tesla model 3'],
'rims': [17,14,13,19,21],
'color':['black','yellow','white','grey','pink'],
'Autopilot$':[3000,3000, 3000,0,0],
'Sunroof$':[0,0,0,2000,2000]})
model3 = df[df['car']=='tesla model 3']
modelx = df[df['car']=='tesla model x']
example = model3.merge(modelx, how='outer',left_on='wk start',right_on='wk start',suffixes=('_model3', '_modelx'))
del example['car_model3']
del example['car_modelx']
example['AUTOPILOT']=example['Autopilot$_model3']+example['Autopilot$_modelx']
example['SUNROOF']=example['Sunroof$_model3']+example['Sunroof$_modelx']
del example['Autopilot$_model3']
del example['Autopilot$_modelx']
del example['Sunroof$_modelx']
del example['Sunroof$_model3']
使用:
说明:
map
和join
展平列中的多索引0
列,由^{loc
删除编辑:
如果使用
^{pr2}$unstack
,则可能缺少一些值,如本示例中所示:因此需要为不包含全部零或全部零的列返回真值(使用
fillna(0)
的原因是什么):用^{} 检查是否至少有一个为真:
相关问题 更多 >
编程相关推荐