Some cell of column is starting from comma so how can i remove it? in Dataframe
Question:
Remove all comma from starting and ending
For Example
id name
1 ,,par, ind, gop, abc
2 ,raj,
3 marl, govin
4 rajjs, sun,,,
Ans
id name
1 par, ind, gop, abc
2 raj,
3 marl, govin
4 rajjs, sun
Answers:
python strip function lets you specify a character to strip from the start and end, so this should work:
df = df['name'].apply(lambda x: x.strip(','))
Or even more simply using the str
handle to access python string functions:
df = df['name'].str.strip(',')
And also with a list comprehension (thanks to @Celius Stingher for this suggestion)
df['name'] = [x.strip() for x in df['name']]
example with data:
import pandas as pd
df = pd.DataFrame(
{
'name': [',,par, ind, gop, abc', ',raj,', 'marl, govin', 'rajjs', 'sun,,,']
})
df = df['name'].str.strip(',')
print(df)
result:
id
name
0
par, ind, gop, abc
1
raj
2
marl, govin
3
rajjs
4
sun
You can perform it faster and more efficient way using list comprehensions, avoiding the need for apply
or lambdas:
df['name'] = [x.strip() for x in df['name']]
Remove all comma from starting and ending
For Example
id name
1 ,,par, ind, gop, abc
2 ,raj,
3 marl, govin
4 rajjs, sun,,,
Ans
id name
1 par, ind, gop, abc
2 raj,
3 marl, govin
4 rajjs, sun
python strip function lets you specify a character to strip from the start and end, so this should work:
df = df['name'].apply(lambda x: x.strip(','))
Or even more simply using the str
handle to access python string functions:
df = df['name'].str.strip(',')
And also with a list comprehension (thanks to @Celius Stingher for this suggestion)
df['name'] = [x.strip() for x in df['name']]
example with data:
import pandas as pd
df = pd.DataFrame(
{
'name': [',,par, ind, gop, abc', ',raj,', 'marl, govin', 'rajjs', 'sun,,,']
})
df = df['name'].str.strip(',')
print(df)
result:
id | name |
---|---|
0 | par, ind, gop, abc |
1 | raj |
2 | marl, govin |
3 | rajjs |
4 | sun |
You can perform it faster and more efficient way using list comprehensions, avoiding the need for apply
or lambdas:
df['name'] = [x.strip() for x in df['name']]