python pandas - 根据另一列的内容将列中的值更改为 bool 值

标签 python pandas dataframe

我有一个像这样的dafatframe:

    A      B   
0  NaN   string1
1  NaN   string2
2  Nan   string1
3  Nan   string1

如何更改 A 列中的所有值,以便根据 B 列中同一索引处的条目是否包含某个字符串“stringX”来更改它们为 bool 值?

最佳答案

我认为您需要分配 bool 掩码,可以使用 eq 来代替 ==或使用assign :

#if need True False values by condition
stringX = "string1"
df['A'] = df['B'] == stringX
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

df['A'] = df['B'].eq(stringX)
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

df = df.assign(A=df['B'].eq(stringX))
print (df)
       A        B
0   True  string1
1  False  string2
2   True  string1
3   True  string1

#if need values of column by condition
df.loc[df['B'] == 'string1', 'A'] = df['B'] 
print (df)
         A        B
0  string1  string1
1      NaN  string2
2  string1  string1
3  string1  string1

#if need scalar by condition
df.loc[df['B'] == 'string1', 'A'] = 1
print (df)
     A        B
0    1  string1
1  NaN  string2
2    1  string1
3    1  string1

#if need if else condition with 2 scalars
df['A'] = np.where(df['B'] == 'string1', 1, 2)
print (df)
   A        B
0  1  string1
1  2  string2
2  1  string1
3  1  string1

关于python pandas - 根据另一列的内容将列中的值更改为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45672516/

相关文章:

python dask dataframes - 连接 groupby.apply 输出到单个数据帧

python - 我需要将 Pandas df 转换为具有制表符分隔分隔和多行的文本字符串

python - 将 df.groupby...max() 结果输入新列。 Pandas

python 文本小部件获取方法

python - 使用 ~isin([list_of_substrings]) 过滤 Dataframe

python - Pandas (如何修复): List is actually string and the value of length is misleading

Python - 发出 HTTP POST 请求,为什么我的有效负载最终以表单形式出现?

python - 将 JSON 列快速转换为 Pandas 数据框

python - 如何使用python-pandas在apply函数中调用数据帧的索引值作为arg?

python - 与 NaN 相等的逐元素比较