gpt4 book ai didi

python - 按列条件计算的 DataFrame 列

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:16 25 4
gpt4 key购买 nike

我是 Python 的新手,我正在尝试根据同一数据框的另一列的条件计算数据框的新列。

我有一个包含 A、B、C、D、E 列的 DataFrame。

我需要计算新的 F 列:

F = A - B if E == 'Y'
F = A - (C + D) if E == 'N'

我尝试使用函数 Apply 但它不起作用。

这是我的代码:

def my_funcion(column): 
if column == 'N' :
return df['B']
if column== 'Y' :
return (df['C'] + df['D'])
df['F'] = df['A'] - df.apply(myfunction(df['E'], axis=1)

但它向我显示了这个错误:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 0'

最佳答案

我想你可以使用 numpy.where :

如果 E 中只有 YN 值的解决方案:

np.random.seed(145)
df = pd.DataFrame(np.random.randint(10,size=(5,4)), columns=list('ABCD'))
df['E'] = ['Y'] * 3 + ['N'] * 2

df['F'] = np.where(df['E'] == 'Y', df['A'] - df['B'], df['A'] - (df['C'] + df['D']))
print (df)

A B C D E F
0 5 5 6 7 Y 0
1 2 5 8 5 Y -3
2 1 2 0 8 Y -1
3 4 5 8 9 N -13
4 1 6 7 6 N -12

如果 E 列中不仅有 NY 的解决方案:

np.random.seed(145)
df = pd.DataFrame(np.random.randint(10,size=(5,4)), columns=list('ABCD'))
df['E'] = ['Y'] * 2 + ['N'] * 2 + ['X']

df['F'] = np.where(df['E'] == 'Y', df['A'] - df['B'],
np.where(df['E'] == 'N', df['A'] - (df['C'] + df['D']), 100))
print (df)

A B C D E F
0 5 5 6 7 Y 0
1 2 5 8 5 Y -3
2 1 2 0 8 N -7
3 4 5 8 9 N -13
4 1 6 7 6 X 100

如果要使用apply(较慢):

def my_funcion(column): 
if column['E'] == 'Y' :
return column['B']
if column['E'] == 'N' :
return (column['C'] + column['D'])

df['F'] = df['A'] - df.apply(my_funcion, axis=1)
print (df)

A B C D E F
0 5 5 6 7 Y 0
1 2 5 8 5 Y -3
2 1 2 0 8 N -7
3 4 5 8 9 N -13
4 1 6 7 6 N -12

关于python - 按列条件计算的 DataFrame 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com