熊猫数据框按列分组,并基于计数分别更新另一列行

时间:2019-12-03 13:04:23

标签: pandas dataframe pandas-groupby

输入数据框

data = {

'org_id' :[79,80,21,36,40,7,10,9,12,24],
'r_id' : [79,80,20,20,20,7,7,9,12,12],
'Type_id' : ['P','P','C','C','C','P','C','P','P','C'],
'grp_id': ['g54','g55','g13','g13','g13','g6','g6','g7','g8','g8']

}
df2 = pd.DataFrame.from_dict(data)
df2


  Out[271]: 
       org_id  r_id Type_id grp_id
    0      79    79       P    g54
    1      80    80       P    g55
    2      21    20       C    g13
    3      36    20       C    g13
    4      40    20       C    g13
    5       7     7       P     g6
    6      10     7       C     g6
    7       9     9       P     g7
    8      12    12       P     g8
    9      24    12       C     g8

输出数据框

数据= {

'org_id' :[79,80,21,36,40,7,10,9,12,24],
'r_id' : [79,80,20,20,20,7,7,9,12,12],
'Type_id' : ['C','C','C','C','C','P','C','C','P','C'],
'grp_id': ['g54','g55','g13','g13','g13','g6','g6','g7','g8','g8']

}

df3 = pd.DataFrame.from_dict(data)
df3

预期输出:

    Out[270]: 
   org_id  r_id Type_id grp_id
0      79    79       C    g54
1      80    80       C    g55
2      21    20       C    g13
3      36    20       C    g13
4      40    20       C    g13
5       7     7       P     g6
6      10     7       C     g6
7       9     9       C     g7
8      12    12       P     g8
9      24    12       C     g8

基于列(grp_id)上的组计数,如果该值等于one(1),则将type_id更改为“ C”

例如。 g54和g55仅出现一次,因此type_id ='C',g13和g6出现多次,所以我不更改该类型。谢谢。

1 个答案:

答案 0 :(得分:1)

对所有重复项,将Series.whereSeries.duplicated constructor(props){ super(props) this.state = { valueP: '', quantity: '', }} ... <View style={Styles.type12Container}> <View style={Styles.inputContainer}> <Picker value={this.state.valueP} style={Styles.picker} mode= "dropdown" prompt= "XXX" selectedValue = {this.state.valueP} onValueChange = {(val) => { this.setState({valueP: val}}}> <Picker.Item label="P 1" value="1" /> <Picker.Item label="P 2" value="2"/> <Picker.Item label="P 3" value="3" /> </Picker> </View> <View style={Styles.inputContainer}> <TextInput value={this.state.quantity} style={Styles.inputStyle} onChangeText={(val) => this.setState({quantity: val})} /> </View> <View style={Styles.button1Container}> <TouchableOpacity onPress={this.addConv} style={Styles.buttonAdd}> <Text style={Styles.button1Text}>Add</Text> </TouchableOpacity> </View> <View style={Styles.output}> <View> <Text style={Styles.button1Text}>products and quantity items</Text> </View> </View> </View> 一起使用掩码:

keep=False