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
3
  • you don't have a loop here though Commented Nov 4, 2021 at 11:28
  • Check this post stackoverflow.com/questions/16476924/… Commented Nov 4, 2021 at 11:31
  • Are you want Printing, because you can do with out for-loop? Commented Nov 4, 2021 at 11:33

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

4 Comments

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)
do you now why in this case i can did it and the first case does not iterate? thank you @Sangkeun Park
@tamo007 You can do it but, it should make the code like this. I added another way as you want to make it work
@SangkeunPark - never use apply here - stackoverflow.com/questions/54432583/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.