根据其他列的条件填充空的 pandas 列 [英] Fill empty pandas column based on condition on others columns
本文介绍了根据其他列的条件填充空的 pandas 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下玩具数据框:
Suppose I have the following toy dataframe:
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['tom', 10], ['nick', 15], ['juli', 14]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
df
,然后创建一个空列,稍后再填充:
and I create an empty column which I want to fill later:
df['foo'] = df.apply(lambda _: '', axis=1)
我想根据其他两列的条件填充空白列。例如:
I want to fill the empty column based on conditions on the other two columns. For example:
if (df['Name']=='tom' and df['Age']==10):
df['foo'] = 'x1'
我遇到以下错误:
系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我在做什么错了?
推荐答案
数据帧需要以不同的方式索引和访问:
Dataframe needs to be indexed and accessed differently:
df['foo'] = ''
df.loc[(df['Name'] == 'tom') & (df['Age'] == 10), 'foo'] = 'x1'
这篇关于根据其他列的条件填充空的 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文