I have a pandas data frame with two columns. I need to change the values of the first column without affecting the second one and get back the whole data frame with just first column values changed. How can I do that using apply in pandas?
我有一个有两列的pandas数据框。我需要更改第一列的值而不影响第二列,只需更改第一列值即可返回整个数据框。我怎么能用熊猫申请呢?
3 个解决方案
#1
149
Given a sample dataframe df
as:
给定样本数据帧df为:
a,b
1,2
2,3
3,4
4,5
what you want is:
你想要的是:
df['a'] = df['a'].apply(lambda x: x + 1)
that returns:
返回:
a b
0 2 2
1 3 3
2 4 4
3 5 5
#2
24
You don't need a function at all. You can work on a whole column directly.
你根本不需要一个功能。您可以直接处理整个列。
Example data:
示例数据:
>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df
a b c
0 100 200 300
1 1000 2000 3000
Half all the values in column a
:
列a中的所有值的一半:
>>> df.a = df.a / 2
>>> df
a b c
0 50 200 300
1 500 2000 3000
#3
10
For a single column better to use map()
, like this:
对于单个列,最好使用map(),如下所示:
df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])
a b c
0 15 15 5
1 20 10 7
2 25 30 9
df['a'] = df['a'].map(lambda a: a / 2.)
a b c
0 7.5 15 5
1 10.0 10 7
2 12.5 30 9
#1
149
Given a sample dataframe df
as:
给定样本数据帧df为:
a,b
1,2
2,3
3,4
4,5
what you want is:
你想要的是:
df['a'] = df['a'].apply(lambda x: x + 1)
that returns:
返回:
a b
0 2 2
1 3 3
2 4 4
3 5 5
#2
24
You don't need a function at all. You can work on a whole column directly.
你根本不需要一个功能。您可以直接处理整个列。
Example data:
示例数据:
>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df
a b c
0 100 200 300
1 1000 2000 3000
Half all the values in column a
:
列a中的所有值的一半:
>>> df.a = df.a / 2
>>> df
a b c
0 50 200 300
1 500 2000 3000
#3
10
For a single column better to use map()
, like this:
对于单个列,最好使用map(),如下所示:
df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])
a b c
0 15 15 5
1 20 10 7
2 25 30 9
df['a'] = df['a'].map(lambda a: a / 2.)
a b c
0 7.5 15 5
1 10.0 10 7
2 12.5 30 9