python - 更新 Pandas 中满足特定条件的行值

标签 python pandas indexing iterator mask

假设我有以下数据框:

table

更新 featanother_feat 列的值的最有效方法是什么/strong>?

是这个吗?

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

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

所以要明确我的目标是什么:

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

最佳答案

我认为你可以使用 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

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

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

另一个常用选项是使用 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

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

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

如果可以使用多个条件,请使用多个 numpy.wherenumpy.select :

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

关于python - 更新 Pandas 中满足特定条件的行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909977/

相关文章:

python - Discord.py中的延迟命令

python - 谁能告诉我为什么这个 png 每次遇到边界时都会创建一个克隆?

pandas - 使用索引作为循环变量连接多个数据帧

indexing - Cypress,获取 th 元素的索引以供稍后使用它的 td 元素

python - 插入运行中的计数器

python - 如何在python中实现chmod u-w

python - 如何根据 pandas groupby 中的另一个系列获得最大值

python - pd.DataFrame(数据,列= [])。如何传递带有嵌套字典的数据?

python - 获得滚动百分位数排名的快速方法

indexing - openssl 的字段数量错误