0

I have the following dataframe:

dct = {"A": ["M1", "M1", "M1", "M2", "M2", "M2", "M4", "M4", "M4"], 
       "B": ["S1", "S1", "S3", "S3", "S4", "S4", "S2", "S2", "S2"], 
       "C": ["a", "n", "cb", "mk", "bg", "dgd", "rb", "cb", "uyi"], 
       "D": [3, 2, 5, 8, 10, 1, 2, 2, 7], 
       "E": [4, 3, 6, 8, 9, 4, 3, 0, 8]}

df = pd.DataFrame(dct)

df would yield:

    A   B    C   D  E
0  M1  S1    a   3  4
1  M1  S1    n   2  3
2  M1  S3   cb   5  6
3  M2  S3   mk   8  8
4  M2  S4   bg  10  9
5  M2  S4  dgd   1  4
6  M4  S2   rb   2  3
7  M4  S2   cb   2  0
8  M4  S2  uyi   7  8

Now I would like to add a value to each value of each row of the dataframe as follows:

for i in range(len(df.index)):
    row = df.iloc[i, :]
    row["F"] = "TEMP_{}".format(i)

Why this doesn't work?

I have been looking into pandas documentation, And I understand that I may be getting a copy of df.iloc[i, :], but I would like to know a solution for this problem if possible

Any help is much appreciated!!

5
  • There’s no need to use a loop for this, df[“F”] = “TEMP” will suffice. Commented Mar 25, 2020 at 2:35
  • So more formally, its row["F"] = "TEMP_{}.format(i)" Commented Mar 25, 2020 at 2:48
  • Where i is the index position? Commented Mar 25, 2020 at 2:49
  • Yes correct... But imagine this is any value from a different list Commented Mar 25, 2020 at 2:55
  • How about df[“F”] = [f”Temp_{elem}” for elem in some_list] ? Commented Mar 25, 2020 at 2:58

2 Answers 2

2

First iloc is using the position to assign the value , you can check with loc

for i in range(len(df.index)):
    df.loc[i, 'F']="TEMP"
Sign up to request clarification or add additional context in comments.

Comments

1

If you want all the values in the new column to say 'Temp' you can just say:

df["F"] = "TEMP"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.