更新pandas中满足特定条件的行值

Sta*_*nko 56 python iterator pandas

说我有以下数据帧:

表

更新列featanother_feat的值的最有效方法是什么,其中2号

是这个吗?

for index, row in df.iterrows():
    if df1.loc[index,'stream'] == 2:
       # do something
Run Code Online (Sandbox Code Playgroud)

更新: 如果我有超过100列怎么办?我不想明确命名我想要更新的列.我想将每列的值除以2(流列除外).

所以要清楚我的目标是什么:

将所有值除以具有流2的所有行中的2,但不更改流列

jez*_*ael 117

我想loc如果你需要将两列更新为相同的值,你可以使用它:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value
Run Code Online (Sandbox Code Playgroud)

如果您需要单独更新,则使用以下一个选项:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value
Run Code Online (Sandbox Code Playgroud)

另一个常见选择是使用numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value
Run Code Online (Sandbox Code Playgroud)

编辑:如果您需要stream在没有条件的情况下划分所有列True,请使用:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0
Run Code Online (Sandbox Code Playgroud)

  • @Stanko - 我认为这是另一个问题 - 您需要以某种方式选择这个“100”列。例如,如果需要`100`第一列,使用`df.columns[:100]`然后传递给`loc`。 (2认同)

Tha*_*nos 5

您可以对 执行相同的操作.ix,如下所示:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315
Run Code Online (Sandbox Code Playgroud)

编辑

在额外信息之后,以下内容将返回所有列(满足某些条件),其值减半:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
Run Code Online (Sandbox Code Playgroud)

  • `ix` 现已弃用。 (15认同)