Reputation: 69
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
Upvotes: 1
Views: 1703
Reputation: 501
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)
Upvotes: 0
Reputation: 45
This is how I would approach the problem:
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
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:
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!
Upvotes: 1
Reputation: 501
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'
Upvotes: 1
Reputation: 69
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"
Upvotes: 1