向带条件Pandas系列添加新列

w6lpcovy  于 2023-01-24  发布在  其他
关注(0)|答案(3)|浏览(119)

我有一个叫做“erm”的 Dataframe ,如下所示:enter image description here
如果erm['Calcul']的值为4,我想添加一个新列'typeRappel' xith value = 1。

# IF ( calcul = 4 ) TypeRappel = 1.
# erm.loc[erm.Calcul = 4, "typeRappel"] = 1
#erm["typeRappel"] = np.where(erm['Calcul'] = 4.0, 1, 0)
# erm["Terminal"] = ["1" if c = "010" for c in erm['Code']]
# erm['typeRappel'] = [ 1 if x == 4 for x in erm['Calcul']]

import numpy as np
import pandas as pd

erm['typeRappel'] = [ 1 if x == 4 for x in erm['Calcul']]

但是这段代码向我发送了如下错误:enter image description here
可能是什么问题?

# IF ( calcul = 4 ) TypeRappel = 1.
# erm.loc[erm.Calcul = 4, "typeRappel"] = 1
#erm["typeRappel"] = np.where(erm['Calcul'] = 4.0, 1, 0)
# erm["Terminal"] = ["1" if c = "010" for c in erm['Code']]
# erm['typeRappel'] = [ 1 if x == 4 for x in erm['Calcul']]

import numpy as np
import pandas as pd

erm['typeRappel'] = [ 1 if x == 4 for x in erm['Calcul']]
fdbelqdn

fdbelqdn1#

您可以使用lambda实现您想要的结果

import pandas as pd

df = pd.DataFrame(
    data=[[1,2],[4,5],[7,8],[4,11]],
    columns=['Calcul','other_col']
)
df['typeRappel'] = df['Calcul'].apply(lambda x: 1 if x == 4 else None)

这将导致
| 计算|其他列|拉攀式|
| - ------|- ------|- ------|
| 1个|第二章|钠氮|
| 四个|五个|1.0分|
| 七|八个|钠氮|
| 四个|十一|1.0分|

iaqfqrcu

iaqfqrcu2#

你有两个办法

第一种方式:

使用from.loc方法,因为只有一个条件

df['new']=None
df.loc[df.calcul.eq(4), 'new'] =1

**第二种方法:**使用numpy.select方法

import numpy as np
cond=[df.calcul.eq(4)]
df['new']= np.select(cond, [1], None)
p4tfgftt

p4tfgftt3#

import numpy as np
import pandas as pd
#erm['typeRappel']=None
erm.loc[erm.Calcul.eq(4), 'typeRappel'] = 1

import numpy as np
cond=[erm.Calcul.eq(4)]
erm['ok']= np.select(cond, [1], None)

相关问题