Paste list into cells matching column conditions

Consider df

   A  B  C
0  3  2  1
1  4  2  3
2  1  4  1
3  2  2  3

I want to add another column "D", so D contains different lists based on conditions on "A", "B"and"C"

   A  B  C  D
0  3  2  1  [1,0]
1  4  2  3  [1,0]
2  1  4  1  [0,2]
3  2  2  3  [2,0]

My code snippet looks like this:

df['D'] = 0
df['D'] = df['D'].astype(object)

df.loc[(df['A'] > 1) & (df['B'] > 1), "D"] = [1,0]
df.loc[(df['A'] == 1) , "D"] = [0,2]
df.loc[(df['A'] == 2) & (df['C'] != 0) , "D"] = [2,0]

When I try to run this code, it throws the following error:

ValueError: Must have equal len keys and value when setting with an iterable

I converted the column to type Objectas suggested here , but still with an error.

I can conclude that pandas is trying to iterate over the elements of the list and assigns each of these values ​​to the cells, where when I try to assign the entire list to all the cells that meet the criteria.

Is there any way to assign lists in the way described above?

+4
source share
3

Series, list shape length df:

df.loc[(df['A'] > 1) & (df['B'] > 1), "D"] = pd.Series([[1,0]]*df.shape[0])
df.loc[(df['A'] == 1) , "D"] = pd.Series([[0,2]]*df.shape[0])
df.loc[(df['A'] == 2) & (df['C'] != 0) , "D"] = pd.Series([[2,0]]*df.shape[0])
print (df)
   A  B  C       D
0  3  2  1  [1, 0]
1  4  2  3  [1, 0]
2  1  4  1  [0, 2]
3  2  2  3  [2, 0]
+3

cond1 = df.A.gt(1) & df.B.gt(1)
cond2 = df.A.eq(1)
cond3 = df.A.eq(2) & df.C.ne(0)

df['D'] = cond3.map({True: [2, 0]}) \
  .combine_first(cond2.map({True: [0, 2]})) \
  .combine_first(cond1.map({True: [1, 0]})) \

df

enter image description here

+3

. .

, jezrael piRSquared, .

, , . , list, list string typecasting.

df.loc[(df['A'] > 1) & (df['B'] > 1), "D"] = '[1,0]'
df.loc[(df['A'] == 1) , "D"] = '[0,2]'
df.loc[(df['A'] == 2) & (df['C'] != 0) , "D"] = '[2,0]'

This may not be applicable to all users, but I can definitely think of situations where that would be enough.

+1
source

Source: https://habr.com/ru/post/1655927/


All Articles