0

Im using python, and i have some difficulties to loop over rows in python. my dataframe contains 3 columns : id, val1, size. i want to create column col1 based on size. Il trying this code and my code is never inside the first condition . How should i correct it please. Let's say that i don't won't something working with other method, im trying just to cirrect my own code.

Friendly,

Sample of data

data = [['x1', 100, 1], ['x2', 200, 2], ['x3', 300, 1]]
df = pd.DataFrame(data, columns = ['id', 'val1', 'size'])

code

if (df['size'] == 2) is True:
  df['col1'] = df['val1']
  print("1")
else:
  pass
tamo007
  • 276
  • 1
  • 12

3 Answers3

4

Do you want print? You can do that without loop like below:

df['col1'] = np.where(df['size'] == 2, df['val1'], np.nan)

Output:

>>> df
    id  val1    size    col1
0   x1  100     1   NaN
1   x2  200     2   200.0
2   x3  300     1   NaN
Mahrkeenerh
  • 1,104
  • 1
  • 9
  • 25
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
2
df['col1'] = df.loc[df['size'] == 2, 'val1']
print(df)
   id  val1  size   col1
0  x1   100     1    NaN
1  x2   200     2  200.0
2  x3   300     1    NaN
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
1

You can make col1 if you edit your code like this:

data = [['x1', 100, 1], ['x2', 200, 2], ['x3', 300, 1]]
df = pd.DataFrame(data, columns=['id', 'val1', 'size'])

col1 = []
for i, row in df.iterrows():
    if row['size'] == 2:
        col1.append(row['val1'])
    else:
        col1.append(None)
df['col1'] = pd.Series(col1)

print(df)

Another way is:

def func(df):
    if df['size'] == 2:
        return df['val1']
    else:
        return None

df['col1'] = df.apply(func, axis=1)
print(df)

This will print:

   id  val1  size   col1
0  x1   100     1    NaN
1  x2   200     2  200.0
2  x3   300     1    NaN
Park
  • 2,446
  • 1
  • 16
  • 25
  • i saw that you did a loop . Here is an example of ietrating that i did without loop **def funt1(df): if (df['size'] == 2 ): val = 'Valu1' else: val= 'Valu2' return val df['col1'] = df.apply(funt1, axis=1)** – tamo007 Nov 04 '21 at 11:38
  • do you now why in this case i can did it and the first case does not iterate? thank you @Sangkeun Park – tamo007 Nov 04 '21 at 11:39
  • @tamo007 You can do it but, it should make the code like this. I added another way as you want to make it work – Park Nov 04 '21 at 11:51
  • @SangkeunPark - never use `apply` here - https://stackoverflow.com/questions/54432583/when-should-i-not-want-to-use-pandas-apply-in-my-code/54432584#54432584 – jezrael Nov 04 '21 at 11:51