等效于Python pandas 替换 [英] Python pandas equivalent for replace

查看:93
本文介绍了等效于Python pandas 替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,有一个相当有用的replace函数. 本质上,它在数据帧的给定列中进行有条件的重新分配. 可以这样使用: replace(df$column, df$column==1,'Type 1');

In R, there is a rather useful replace function. Essentially, it does conditional re-assignment in a given column of a data frame. It can be used as so: replace(df$column, df$column==1,'Type 1');

在大熊猫中实现相同目标的好方法是什么?

What is a good way to achieve the same in pandas?

我应该将lambda与apply一起使用吗? (如果是这样,我如何获得给定列的引用,而不是整个行的引用.)

Should I use a lambda with apply? (If so, how do I get a reference to the given column, as opposed to a whole row).

我应该在data_frame.values上使用np.where吗? 似乎我在这里错过了一件非常明显的事情.

Should I use np.where on data_frame.values? It seems like I am missing a very obvious thing here.

任何建议都值得赞赏.

推荐答案

pandas也具有replace方法:

In [25]: df = DataFrame({1: [2,3,4], 2: [3,4,5]})

In [26]: df
Out[26]: 
   1  2
0  2  3
1  3  4
2  4  5

In [27]: df[2]
Out[27]: 
0    3
1    4
2    5
Name: 2

In [28]: df[2].replace(4, 17)
Out[28]: 
0     3
1    17
2     5
Name: 2

In [29]: df[2].replace(4, 17, inplace=True)
Out[29]: 
0     3
1    17
2     5
Name: 2

In [30]: df
Out[30]: 
   1   2
0  2   3
1  3  17
2  4   5

或者您可以使用numpy样式的高级索引:

or you could use numpy-style advanced indexing:

In [47]: df[1]
Out[47]: 
0    2
1    3
2    4
Name: 1

In [48]: df[1] == 4
Out[48]: 
0    False
1    False
2     True
Name: 1

In [49]: df[1][df[1] == 4]
Out[49]: 
2    4
Name: 1

In [50]: df[1][df[1] == 4] = 19

In [51]: df
Out[51]: 
    1   2
0   2   3
1   3  17
2  19   5

这篇关于等效于Python pandas 替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆