Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何对数据帧中的行使用if-elif_Python_Pandas_If Statement - Fatal编程技术网

Python:如何对数据帧中的行使用if-elif

Python:如何对数据帧中的行使用if-elif,python,pandas,if-statement,Python,Pandas,If Statement,我有一个数据框,我想在表的行上添加一个使用if-elif条件的列。我正在使用if-elif语句,但它不起作用。 我们不能对数据帧使用条件statemet吗 这是我的密码: import pandas as pd df = pd.DataFrame({'c1': ['a', 'a', 'q', 'a'], 'c2': ['b', 'e', 'b', 'f'], 'c3': ['c', 'f', 'c', 'd']}) if [(df['c

我有一个数据框,我想在表的行上添加一个使用if-elif条件的列。我正在使用if-elif语句,但它不起作用。 我们不能对数据帧使用条件statemet吗

这是我的密码:

import pandas as pd
df = pd.DataFrame({'c1': ['a', 'a', 'q', 'a'],
              'c2': ['b', 'e', 'b', 'f'],
               'c3': ['c', 'f', 'c', 'd']})

if [(df['c1']=='a') & (df['c2']=='b')]:
    df['q']= df['c1'] + '+' + df['c2']
elif (df['c1']=='a' & df['c2']=='e'):
    df['q'] = df['c1'] + '*' + df['c2']
else:
    df['q'] = df['c1'] + '-' + df['c2']
新列“q”的内容为:“a+b”、“a+e”、“q+b”、“a+f”

虽然我希望它是:
“a+b”、“a*e”、“q-b”、“a-f”等if语句的矢量化版本是
np.where
。我将条件和可能的结果分配给变量以提高可读性,因为使用嵌套的
np.where
s可能会变得很难理解

cond1 = (df['c1']=='a') & (df['c2']=='b')
cond2 = (df['c1']=='a') & (df['c2']=='e')

case1 = df['c1'] + '+' + df['c2']
case2 = df['c1'] + '*' + df['c2']
case3 = df['c1'] + '-' + df['c2']

df['q'] = np.where(cond1, case1, np.where(cond2, case2, case3))

df
Out: 
  c1 c2 c3    q
0  a  b  c  a+b
1  a  e  f  a*e
2  q  b  c  q-b
3  a  f  d  a-f
使用多个嵌套的
np的可读性更好的形式。其中

m1 = (df['c1']=='a') & (df['c2']=='b')
m2 = (df['c1']=='a') & (df['c2']=='e')

a1 = df['c1'] + '+' + df['c2']
a2 = df['c1'] + '*' + df['c2']
a3 = df['c1'] + '-' + df['c2']

df['q'] = np.select([m1, m2], [a1, a2], default=a3)
print (df)

  c1 c2 c3    q
0  a  b  c  a+b
1  a  e  f  a*e
2  q  b  c  q-b
3  a  f  d  a-f

在您的条件下,不要使用“&”运算符,而是使用“and”。@AnkurSharma请参阅@sky_bird您所说的“不工作”是什么意思?是的,您是对的。“谢谢”和“不起作用”。它显示了一个错误。“序列的真值不明确。请使用a.empty、a.bool()、a.item()、a.any()或a.all()。”这对我很有帮助..thanx!!很高兴能帮上忙,天气真好!