我有一个输入数据框df,我想在其中转换列A...A B asd0 dsf1 ewr2 dfds3 sdf...进入我的预期输出df1: Aa Ab Ac Bb asd 0 0 0 dsf 1 0 0 ewr 1 1 0 dfds 1 1 1 sdf代码:if df['A'] == '' : df1['Aa'] = ''elif df['A'] == 1 : df1['Aa'] == 1elif df['A'] == 0 : df1['Aa'] == 0else: df1['Aa'] == 1错误:if df['A'] == '' : File "C:\Python\Python38\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__ raise ValueError( ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().excel中类似的公式 B2 =IF(A2=1,1,IF(A2="","",IF(A2=0,0,1)))相似地; C2 = IF(A2=2,1,IF(A2="","",IF(A2=0,0,1)))尝试用 python 实现类似的东西。请帮忙!!逻辑:if value in df['A'] == ''; new column 'Aa,Ab,Ac' in df1 == ''if value in df['A'] == 1; new column 'Aa' in df1 == 1, and rest (Ab,Ac) == 0if value in df['A'] == 2; new column 'Aa, Ab' in df1== 1, and rest (Ac) == 0if value in df['A'] == 3; new column 'Aa,Ab,Ac' in df1 == 1因此,流程可能类似于:df1:A Aa Ab Ac Bb asd0 0 0 0 dsf1 1 0 0 ewr2 1 1 0 dfds3 1 1 1 sdf稍后只需删除列即可A。所以Final df1 Aa Ab Ac Bb asd 0 0 0 dsf 1 0 0 ewr 1 1 0 dfds 1 1 1 sdf
2 回答
守着一只汪
TA贡献1872条经验 获得超3个赞
找到了一种方法来做到这一点,只需将其放入函数中,您也可以将其用于其他嵌套循环
conditions = [
(df['A'] == 0),
(df['A'] == 1),
(df['A'] > 1)]
choices = [0, 1, 1]
df1['Aa'] = np.select(conditions, choices, default='null')
慕斯709654
TA贡献1840条经验 获得超5个赞
IIUC,尝试:
import pandas as pd
df = pd.DataFrame({'a':["",0,1,2,3]})
df['new_a'] = pd.to_numeric(df['a'], errors='coerce')
df['Aa'] = df['new_a'].apply(lambda x: np.nan if math.isnan(x) else (0 if x==0 else (OTHER CONDITION)))
您可以使用类似的逻辑来创建“Ab”、“Ac”和“Bb”
添加回答
举报
0/150
提交
取消