我们说我有以下数据框:
date,id,value
1/1/2017,5,300
1/1/2017,51,300
1/1/2017,54,300
1/2/2017,5,100
1/2/2017,51,100
1/2/2017,54,100
我有一个字典映射id
到调整因子:
{5: 20, 51: 23.5, 54:10}
我希望add
与我的数据框中的id
到value
列对应的因素,从而产生:
date,id,value,adjusted_value
1/1/2017,5,300,300+20=320
1/1/2017,51,310,310+23.5=333.5
1/1/2017,54,320,320+10=330
1/2/2017,5,110,110+20=130
1/2/2017,51,120,120+23.5=143.5
1/2/2017,54,130,130+10=140
有一种简单的方法吗?
答案 0 :(得分:1)
我认为你正在寻找ngroup,cumcount和mapping,即
<Input
ref='barcode'
style={styles.barcodeInput}
autoFocus={true}
onChangeText={(text) => {
this.setState({barcodeNumber: text});
}}
onSubmitEditing={(event)=> {
this.getResult();
}}
placeholder='Barcode Number'/>
getResult(){
if ( this.state.barcodeNumber === '021200507878' ){
this.setState({backgroundColor: '#2ecc71', status:'success'});//green
} else {
this.setState({backgroundColor: '#c0392b', status:'error'}); //red
}
this.clearText('barcode');
}
clearText(fieldName) {
this.refs[fieldName].setNativeProps({text: ''});
}
输出:
date id value new 0 1/1/2017 5 300 320.0 1 1/1/2017 51 300 333.5 2 1/1/2017 54 300 330.0 3 1/2/2017 5 100 130.0 4 1/2/2017 51 100 143.5 5 1/2/2017 54 100 140.0
解释
x = df.groupby('date')
d = {5: 20, 51: 23.5, 54: 10}
df['new'] = (x.cumcount()+x.ngroup())*10 +df['id'].map(d)+df['value']
0 0 1 1 2 2 3 1 4 2 5 3
(x.cumcount()+x.ngroup()
0 300 1 310 2 320 3 110 4 120 5 130 dtype: int64
答案 1 :(得分:0)
一衬垫:
df['adjusted_value'] = df.apply(lambda x: dictionary[x['id']] + x['value'] , axis=1)
更详细:
df['adjusted_value'] = [dictionary[i] for i in df['id']]
df['adjusted_value'] = df['adjusted_value'] + df['value']