【问题标题】:How to iterate dataframe row and compare the values in if condition如何迭代数据框行并比较if条件中的值
【发布时间】:2020-08-17 08:36:22
【问题描述】:

这是我的代码,我试图按列比较两个数据帧的值并递增 1。代码给出了错误下方的错误。请在这里帮助我。

df_select = pd.read_csv(path,low_memory=False)
df_datahub = pd.read_csv(path1,low_memory=False)
df_select_i = df_select.set_index('medical_event_vod__c')
df_datahub_i = df_datahub.set_index('intact_id')

i, j, k, l, m = 0, 0, 0, 0, 0
for index, row in df_select_i.iterrows():
    m += 1
    if index in df_datahub_i.index:
        i += 1
        df_temp_select = df_select_i.loc[index]
        df_temp_datahub = df_datahub_i.loc[index]

        if  df_temp_select['createddate'] == df_temp_datahub['src_sys_cr8_ts'] :
            k+=1
        else:
            j+=1
    else:
        l += 1
print(m)
print(i)
print(j)
print(k)
print(l)

这是错误:

if  df_temp_select['createddate'] == df_temp_datahub['src_sys_cr8_ts'] :
raise ValueError(
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or 
    a.all().

【问题讨论】:

  • 您正在将数组与值进行比较。打印 df_temp_select['createddate'] 和 df_temp_datahub['src_sys_cr8_ts'] 你会看到一个是 array/series/list 而另一个不是。
  • 这就是你要找的。 stackoverflow.com/questions/53830081/…

标签: python pandas


【解决方案1】:

这里的问题是您将 pd.Series 与一个值进行比较,因此您将有多个 True 和多个 False 值,如上例所示。这当然是模棱两可的,因为条件既不是真也不是假。

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【讨论】:

    【解决方案2】:

    当您将两个系列(例如您的列)与== 进行比较时,它会逐元素比较它们并返回一个系列。正如错误提示的那样,您可以在返回的 Series 上使用 .all() 来检查所有比较是否都是 True

    例子:

    In [1]: import pandas as pd
    
    In [2]: x = pd.Series([1,2,3])
    
    In [3]: y = pd.Series([1,3,2])
    
    In [4]: x == y
    Out[4]: 
    0     True
    1    False
    2    False
    dtype: bool
    
    In [5]: (x == y).all()
    Out[5]: False
    

    【讨论】:

    • if (df_temp_select == df_temp_datahub).all() : self, other = _align_method_FRAME(self, other, axis, level=None, flex=False) raise ValueError( ValueError: 只能比较相同-标记的 DataFrame 对象
    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 2021-10-20
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多