0

I wanted to change a contiguous block of row values in one column in one go.

In the end I ended up with this that does the job but I kinda think there must be a neater way.

df = pd.read_excel('ja.xlsx')
df  # echo the contents of the df

for index, row in df.iterrows():
    if index < 4:
        df.loc[ index, "my_col_name"] = 'yes'
    else:
        df.loc[ index, "my_col_name"] = 'no'

any suggestions?

Thanks!

jacanterbury
  • 1,435
  • 1
  • 26
  • 36
  • 2
    Similar to this question? https://stackoverflow.com/questions/28975758/replace-an-entry-in-a-pandas-dataframe-using-a-conditional-statement or this?https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column – johnchase Oct 19 '17 at 19:22
  • thanks for those - I did have a hunt around before asking but neither of those came up with the search i made – jacanterbury Oct 19 '17 at 19:34

1 Answers1

1
df["my_col_name"]='yes'
df.loc[df.index>=4,"my_col_name"]='no'

or

df['new1']=np.where(df.index>=4,'no','yes')
BENY
  • 317,841
  • 20
  • 164
  • 234
  • 1
    I knew there would be a better way - turns out there are two better ways :-) though the on-liner edges it for conciseness without any obfuscation. Many thanks – jacanterbury Oct 19 '17 at 19:30