您好我有一个pandas数据帧,我有一个A列。
data = pandas.DataFrame()
data['A']= [numpy.random.choice([1,2,3,4,5,6]) for i in range(10)]
我想在A上添加B列条件(当A = 1然后B = 0,当A> 5然后B = 1时)而不是使用:
data.loc[data['A']==1,'B']=0
data.loc[data['A']>5, 'B']=1
这里我想创建一个函数来执行此操作,条件为dict:{'A = 1':0,'A> 5':1}所以我可以使用add_column({'A = 1': 0,'A> 5':1},'B')执行上面的代码。我认为与经营者打交道是个棘手的任何好主意吗?
def add_column(condition_dict, NewColumnName):
pass
答案 0 :(得分:2)
虽然可能有效的方法,但可能的一种方法是使用eval
函数。
创建输入df
:
import pandas as pd
import numpy as np
data = pd.DataFrame()
data['A']= [np.random.choice([1,2,3,4,5,6]) for i in range(10)]
print(data)
输入df
:
A
0 4
1 3
2 3
3 1
4 1
5 2
6 3
7 6
8 2
9 1
现在,创建了一个函数,使iterates
和dataframe
的每一行condition_dict
以及row
评估匹配value
的时间new column
存储在列表中对于为None
更新的相应行。如果条件都不匹配,则默认为def add_column(df, condition_dict, NewColumnName):
new_values = []
for index, row in df.iterrows():
# if none of the condition matches then put default value
default_value = None
# iterate through each condition to check if any matches
for key, value in condition_dict.items():
expression = 'row.' + key
if(eval(expression)):
default_value = value
# add corresponding rows new value for new column
new_values.append(default_value)
df[NewColumnName] = new_values
:
add_column(data, {'A==1':0, 'A>5':1}, 'B')
print(data)
现在,要调用该函数:
A B
0 4 NaN
1 3 NaN
2 3 NaN
3 1 0.0
4 1 0.0
5 2 NaN
6 3 NaN
7 6 1.0
8 2 NaN
9 1 0.0
输出:
getElementsByClassName