1

I am trying to take links and push them via TinyURL.. I have a dataframe containing Login Links column and I would like to take those individually and add to column 'Tiny URL', the tiny_urlize link.

for index, row in df.iterrows():
    df.loc[index, 'Tiny Url'] = tiny_urlize(row['Login Link'])

The error I am getting looks like this:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

but this is exactly what I am doing. Am I missing something?

4
  • Is df itself a copy (e.g. did you do at some point before df = other_df[some_slice] ? Commented Jan 31, 2019 at 19:02
  • No, I never did that Commented Jan 31, 2019 at 19:05
  • 1
    Can you show how you define your df? Commented Jan 31, 2019 at 19:06
  • It can also be the result of a few methods that you wouldn't necessarily expect to return a copy. For instance df = df.drop_duplicates() could be the culprit. Commented Jan 31, 2019 at 19:13

2 Answers 2

2

This error can pop up for a number of different reasons, a common case for example is that df is a slice of another dataframe. I suspect if you write df = df.copy() before your iterrows you won't get the error.

You can also simplify and speed up your expression by writing it as an apply:

df['Tiny Url'] = df['Login Link'].apply(tiny_urlize)

which I believe will also prevent the warning

Sign up to request clarification or add additional context in comments.

Comments

0

The issue is that you are updating the value of df using loc while looping (which is essentially a slice). Try,

for index, row in df.iterrows():
    row['Tiny Url'] = tiny_urlize(row['Login Link'])

Moreover, pandas has in-built functions which are very efficient for such things, one of them being apply.

df['Tiny Url'] = df['Login Link'].apply(tiny_urlize)

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.