Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

python - How can I assign values to a dataframe with a loop if empty series come up

I am filtering a lot in a bigger Dataframe and putting those results in a new column (different values for each row). Sometimes the filtering end up in an empty Series and I get a "ValueError: Incompatible indexer with Series."

Is there a way that in these cases a "Nan" or a "0" is used?

Here is an example of my problem:

  df=pd.DataFrame(np.arange(0,20).reshape(4,5),columns=["A","B","C","D","E"])
    
    for idx in df.index:
         df.loc[idx,"E"]=df.loc[(df.A>10)&(df.B<11)].C.values

Expected result here: Nan or 0

question from:https://stackoverflow.com/questions/65923307/how-can-i-assign-values-to-a-dataframe-with-a-loop-if-empty-series-come-up

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's probably a slicker way to put this together with np.where() or apply(lambda x: x....) but really you just need to test if the returned value is is an empty dataframe/value, and if it is set your column to zero.

for idx in df.index:
    if len(df.loc[(df.A>10)&(df.B<11)].C.values)==0:
        df.loc[idx,"E"] = 0
    else:
        df.loc[idx,"E"]=df.loc[(df.A>10)&(df.B<11)].C.values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...