嗨,我有一个熊猫数据框,我有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
尽管可能有有效的方法来实现,但一种可能的方法可能是使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句