简体   繁体   中英

Conditional append list for Pandas dataframes

I am using the following code to attempt to filter our specific rows but I am getting an error that says:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

df = pd.DataFrame(rdataset)
plane = 'axial'
contrast = 'T1'

a = []

for slices in range(0,60):
    if df['nSlices']==slices:  #---------------> Problem here ?
        path = df.loc[df['nSlices'].eq(slices) & df['Orient'].eq(plane)  & df['Contrast'].eq(contrast),'Path'].tolist()
        a.append(path)

The error appears because you are trying to compare Series object df['nSlices'] with scalar integer slices . The result of such comparsion is Series object with bool values (try to do print(df['nSlices']==slices) to see it) and you can't use it in if-statement.

To solve the problem just remove if df['nSlices']==slices: to get:

for slices in range(0,60):
    path = df.loc[df['nSlices'].eq(slices) & df['Orient'].eq(plane)  & df['Contrast'].eq(contrast),'Path'].tolist()
    a.append(path)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM