应用和Lambda函数值错误:序列的真值不明确。使用a.empty、a.bool()、a.item()、a.any()或a.all()

2024-10-04 01:35:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过使用Apply和Lambda函数创建一个新列,将'ID'值除以219(如果'Gender'是'femal',如果'Gender'是'Male',则除以393)。首先,我尝试使用“性别”列,该列包含无法使用的分类变量。因此,我创建了一个基于“性别”的二进制列,将0分配给“女性1”分配给“男性”,并使用该列,但不起作用

我仍然得到如下值错误:

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

我的代码是

by_label_out_degree[NormID] = by_label_out_degree.apply(lambda row: row['ID']/ 219 if row['Gender2'] == 0 else row['ID']/ 393,axis=1)

我再次添加我的代码!谢谢你的帮助

values = [
[42785,428855,'Energy','Female'],
[43432,428686,'Trust','Male'],
[43432,428686,'Career','Male'],
[43432,428686,'Personal','Male'],
[43432,428634,'Trust','Female']
]
df: pd.DataFrame = pd.DataFrame(values, columns =['ID','Target','Label','Gender'])
new_df = df.groupby(['Gender','Label']).ID.count().reset_index()
new_df['Gender2'] = new_df.Gender.map({'Female':0,'Male':1})
new_df['NormID'] = new_df.apply(lambda row: row['ID']/219 if row['Gender2'] == 0 else row['ID']/393, axis = 1)

Tags: 代码iddfnewbyoutgenderlabel
1条回答
网友
1楼 · 发布于 2024-10-04 01:35:31

修复

使用列Gender效果很好

values = [
    ['Female', 'Access', 96],
    ['Female', 'Career', 165],
    ['Male', 'Access', 236],
    ['Male', 'Energy', 445]
]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = df.apply(lambda row: row['ID'] / 219 if row['Gender'] == 'Female' else row['ID'] / 393, axis=1)
print(df)

   Gender   Label   ID    newcol
0  Female  Access   96  0.438356
1  Female  Career  165  0.753425
2    Male  Access  236  0.600509
3    Male  Energy  445  1.132316

更好

使用^{}

import numpy as np
import pandas as pd

values = [['Female', 'Access', 96], ['Female', 'Career', 165],
          ['Male', 'Access', 236], ['Male', 'Energy', 445]]
df: pd.DataFrame = pd.DataFrame(values, columns=['Gender', 'Label', 'ID'])
df['newcol'] = np.where(df['Gender'] == 'Female', df['ID'] / 219, df['ID'] / 393)
print(df)

相关问题 更多 >