Python 在pandas中选择、排序和重命名列
我试图找出pandas中的Python 在pandas中选择、排序和重命名列,python,pandas,dplyr,Python,Pandas,Dplyr,我试图找出pandas中的R的select函数等价物。有一个基本的,但它不是给一个指南,我想做什么 raw_data = {'patient': [1, 1, 1, 2, 2], 'obs': [1, 2, 3, 1, 2], 'treatment': [0, 1, 0, 1, 0], 'score': ['strong', 'weak', 'normal', 'weak', 'strong']} df = pd.DataFrame(raw_dat
R的select
函数等价物。有一个基本的,但它不是给一个指南,我想做什么
raw_data = {'patient': [1, 1, 1, 2, 2],
'obs': [1, 2, 3, 1, 2],
'treatment': [0, 1, 0, 1, 0],
'score': ['strong', 'weak', 'normal', 'weak', 'strong']}
df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])
df.rename(columns = {'treatment':'treat'},inplace=True)
df = df.loc[:, ['treat','score','obs']]
Out[89]:
treat score obs
0 0 strong 1
1 1 weak 2
2 0 normal 3
3 1 weak 1
4 0 strong 2
我们可以使用R的
dplyr
select(df, treat=treatment, score, obs) that's it.
如何使用pandas实现这一点?仅使用一行代码进行选择、排序和重命名?pandas中没有等效的选择和重命名方法,是否需要使用类似的解决方案:
df = df.rename(columns = {'treatment':'treat'})[['treat','score','obs']]
#alternative
#df = df[['treatment','score','obs']].rename(columns = {'treatment':'treat'})
print (df)
treat score obs
0 0 strong 1
1 1 weak 2
2 0 normal 3
3 1 weak 1
4 0 strong 2
现在,您可以在python中以
dplyr
的方式执行此操作:
>>从datar.all导入f,tibble,选择
>>>
>>>原始数据=TIBLE(
…患者=[1,1,1,2,2],
…obs=[1,2,3,1,2],
…治疗=[0,1,0,1,0],
…得分=[‘强’、‘弱’、‘正常’、‘弱’、‘强’]
... )
>>>#在python中,关键字参数必须排在最后
>>>#我们指定score=f.score以保持名称不变
>>>选择(原始数据,treat=f.treat,score=f.score,obs=f.obs)
治疗分数obs
0强1
1弱2
2 0正常3
3 1弱1
40强2
我是这个包裹的作者。如果您有任何问题,请随时提交问题