繁体   English   中英

尝试检查另一个 pandas 列中是否存在值时出现长度错误

[英]Length error when trying to check if value exists in another pandas column

我想返回一个反映P2 Actual Scan SiteScoring Site列,但前提是P2 Actual Scan Site被认为是有效的。

输入:

dataframe sites_exams_df包括检查有效性的列Valid Site for Exam? , 像这样:

      SCI    DBN4 Valid Site for Exam?
0      NaN  02L298                  NaN
1      NaN  02L416                  NaN
2      NaN  02L420                  NaN
3   SCI,    02L475               02L475

我当前的 dataframe 与P2 Actual Scan Site

P2 Actual Scan Site
0         -
1    10L445
2    10L445
3    02L475
4    02L475
5    27L400
6    00000C

所需的 Output:

  P2 Actual Scan Site  Scoring Site
0                   -           NaN      
1              10L445        10L445
2              10L445        10L445
3              02L475        02L475
4              02L475        02L475      
5              27L400        27L400
6              00000C           NaN

请注意,最后一个学校代码返回 NaN,因为它不被视为有效站点(以及- )。

所有其他学校代码按原样返回。

当前代码:

# create Scoring Site column
sites_exams_df['Valid Site for Exam?'] = np.where(sites_exams_df[exam].notnull(),sites_exams_df['DBN4'],
                                                  np.nan) # check what scoring sites are there for this exam
valid_sites = sites_exams_df['Valid Site for Exam?'].dropna().values

# attempt 1
df['Scoring Site'] = np.where(df['P2 Actual Scan Site'] in valid_sites,
                              df['P2 Actual Scan Site'],np.nan)

# attempt 2
df['Scoring Site'] = df.apply(lambda x: df['P2 Actual Scan Site'] if x in valid_sites else np.nan)

两者都给我长度错误:

尝试 1 - raise ValueError("Lengths must match to compare") ValueError: Lengths must match to compare

尝试 2 - ValueError: ('Lengths must match to compare', 'occurred at index DBN - Exam')

这应该可以解决您的问题:

# create Scoring Site column
sites_exams_df['Valid Site for Exam?'] = np.where(sites_exams_df[exam].notnull(),sites_exams_df['DBN4'],
                                                  np.nan) # check what scoring sites are there for this exam
valid_sites = list(sites_exams_df['Valid Site for Exam?'].dropna())

df['Scoring Site'] = df['P2 Actual Scan Site'].map(lambda x: x if x in valid_sites else np.nan)

map 是应该使用的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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