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
4 Answers
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'
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
Method: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html
Code:
# Condition: the character 'a' has to be present df['B'].apply(lambda x: x + ', b' if 'a' in x else x)Result:
df A B 0 1 a, b 1 2 a, b 2 3 b
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!
