我想知道是否有一种方法可以将新的 .loc 值分配给数据框以便为该行建立索引。 我在编写代码的地方用 .loc [] 为行建立索引,但是现在我将数据帧随机改组为两组,所以当我用 .loc []对该行进行索引时,因为该行可能在其他数据集中,所以出现了关键错误。
我希望能够在改组后立即为数据分配新的.loc []索引,这样我仍然可以像往常一样进行索引。
例如,我有一个数据框:
length height... water type
4 15.85 14.7240 ... 0.173 orange
92 20.06 17.3565 ... 0.171 orange
155 22.71 15.8040 ... 0.169 apple
142 11.76 12.2355 ... 0.175 pear
91 20.33 16.0785 ... 0.175 apple
给定的索引显示在左侧(即4到91),我想将这些索引值更改为要为其分配的索引值,这是按顺序排列(即0到4)。这样,当我调用.loc [0]时,它将返回第一行,而不是给我一个KeyError,因为该行在另一个数据集中
谢谢。
答案 0 :(得分:0)
来自Pandas文档:
public class TopOpportunityClass{
public static boolean flag = true;
public static void onTopOpportunity(List<Opportunity> opport){
if(flag==true){
List<Opportunity> uptOpp = new List<Opportunity>();
Set<Id> accIds = new Set<Id>();
for(Opportunity opp : opport){
if(opp.AccountId != null){
accIds.add(opp.AccountId);
}
}
Map<Id, List<Opportunity>> accOpportMap = new Map<Id, List<Opportunity>>();
List<Account> accUpdateList = new List<Account>();
for(Opportunity obj : [SELECT id,name, amount,accountId
FROM Opportunity
WHERE accountId IN :accIds ORDER BY amount DESC nulls last]){
List<Opportunity> oppList;
if(accOpportMap.containsKey(obj.accountId)){
oppList = accOpportMap.get(obj.accountId);
}else{
oppList = new List<Opportunity>();
}
oppList.add(obj);
accOpportMap.put(obj.accountId, oppList);
}
for(Id accId : accOpportMap.keySet()){
if(accOpportMap.get(accId).size() > 1 ){
opportunity opp1 = new opportunity(id = accOpportMap.get(accId)[1].id , isTopOpportunityCheck__c = false);
uptOpp.add(opp1);
accUpdateList.add(new Account(id = accId, isTopOpportunity__c = accOpportMap.get(accId)[0].id));
opportunity opp = new opportunity(id = accOpportMap.get(accId)[0].id , isTopOpportunityCheck__c = true);
uptOpp.add(opp);
}else if(accOpportMap.get(accId).size() == 1 ){
accUpdateList.add(new Account(id = accId, isTopOpportunity__c = accOpportMap.get(accId)[0].id));
opportunity opp = new opportunity(id = accOpportMap.get(accId)[0].id , isTopOpportunityCheck__c = true);
uptOpp.add(opp);
}else if(accOpportMap.get(accId).size() == 0){
accUpdateList.add(new Account(isTopOpportunity__c = NULL, id = NULL));
}
flag = false;
}
if(!accUpdateList.isEmpty()){
update accUpdateList;
update uptOpp;
}
}
}
}
//trigger
trigger OpportunityTrigger on Opportunity (after insert, after update){
if(Trigger.isAfter){
TopOpportunityClass.onTopOpportunity(Trigger.new);
}
}
使用带有drop参数的reset_index:
>>> df = pd.DataFrame([('bird', 389.0),
... ('bird', 24.0),
... ('mammal', 80.5),
... ('mammal', np.nan)],
... index=['falcon', 'parrot', 'lion', 'monkey'],
... columns=('class', 'max_speed'))
>>> df
class max_speed
falcon bird 389.0
parrot bird 24.0
lion mammal 80.5
monkey mammal NaN