【问题标题】:iterating and editing in pandas data frame (python)在熊猫数据框(python)中迭代和编辑
【发布时间】:2014-05-01 20:40:57
【问题描述】:

我需要根据另一列的布尔值修改我的 pandas 数据框的一列。假设我有一列值,一列是真/假,并且我想将 1 与相应的布尔真值相加。我尝试使用 iterrows,但这会复制数据框并且不会对其进行修改。

谢谢!

输入:

   val    bool
a   1.0   true
b   2.3   false
...

输出:

   val    bool
a  2.0    true
b  2.3    false

【问题讨论】:

  • df['val'] = df.apply(lambda row: row['val'] + [0,1][row['bool']], axis=1)
  • 不要使用bool作为列名,加上你的值,如果它们应该是布尔值,它们是无效的,它们应该是TrueFalse而不是truefalse

标签: pandas


【解决方案1】:

使用loc 创建布尔掩码并使用此掩码更新值,例如:

In [157]:

df = pd.DataFrame({'a':np.random.randn(5), 'b':[True,False,True,True,False]})
df

Out[157]:
          a      b
0 -1.666632   True
1  1.518392  False
2 -0.340623   True
3 -0.233279   True
4 -0.169503  False

[5 rows x 2 columns]
In [158]:
# determine the locations where we have a True value for the boolean mask
df.loc[df.b==True,'a']
Out[158]:
0   -1.666632
2   -0.340623
3   -0.233279
Name: a, dtype: float64
In [159]:
# now add one
df.loc[df.b==True,'a'] += 1
In [160]:

df
Out[160]:
          a      b
0 -0.666632   True
1  1.518392  False
2  0.659377   True
3  0.766721   True
4 -0.169503  False

[5 rows x 2 columns]

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 2015-12-09
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2014-01-08
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多