1

I've been struggling with one problem for two days that I have with Python and the Pandas package. I am creating a dataframe with filtered data from another csv and then want to export it to csv again. However, I have a problem because I do not know how to add another value to a specific cell without removing the previous one so that it looks more or less like this in CSV. So that I could add this letter b to the second column and the first row where the letter a already exists

enter image description here

1
  • 1
    Can you please add minimal reproducible example outling input/output and the code(if) you have written so far. Commented Jun 19, 2022 at 18:54

4 Answers 4

1

You can use this code It edits all of the rows if you want else you want to edit just first row you can remove for loop and use i=0

for i in df.index:
  if df['B'][i].find('a')>=0:
    df['B'][i] += ', b'
Sign up to request clarification or add additional context in comments.

2 Comments

This is how it solves my problem. I didn't know it would be that simple. I tried with add, append functions. Thanks for the help :)
these methods are for python list not dataframe
1
df_10 = pd.DataFrame({'A': ['xx', '--- bios ---', 'yy', 'zz', '--- os ---'],'B': ['rat', '', 'winter', 'host','']})

I create such a data frame as add to column A and line 2, for example the value "new"

Comments

1

This is how I would approach the problem:

Creating example dataframe

  • Code:

    df = pd.DataFrame(
        data={
            'A': [1, 2, 3],
            'B': ['a', 'a', 'b'],
        }
    )
    
  • Result

    df
    
        A   B
    0   1   a
    1   2   a
    2   3   b
    

Applying function to add character (with comma) only on the rows that meet a condition

This will work for the entire 2nd column (in this example, column ‘B’).

If you’d like to apply this rule only to a specific row of the dataframe, I would only add the following:

Applying function to add character (with comma) only on the rows that meet a condition

  • Code:

    # Condition: the character 'a' has to be present on a selecteed row
    
    row = 0 ## row where you'd like to apply the change
    
    df.loc[row, ['B']] = df.loc[row, ['B']].apply(lambda x: x + ', b' if 'a' in x else x)
    
  • Result:

    df
    
        A   B
    0   1   a, b
    1   2   a
    2   3   b
    

Hope this solutions helps!

Comments

0

This is very very faster and better

def f(s):
    if s.find('a')>=0:
        return s+', b'
    return s
df['B']=df['B'].apply(func=f)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.