Bitopan Gogoi
Bitopan Gogoi

Reputation: 125

Compute a row in Pandas operating other columns

I have a dataframe like this-

df = pd.DataFrame{"a":[2.22, 3.444, 4.3726],"b":[3.44, 5.96, 7.218] }

I need to compute another column c by the following operation on column a-

c = len(str(a))-len(str(int(a)))-1

Tried different methods but not able to achieve.

Upvotes: 1

Views: 40

Answers (2)

jezrael
jezrael

Reputation: 863501

If there is different digits after . is possible use Series.str.len with Series.astype:

df = pd.DataFrame({"a":[2.22, 3.444, 4.3726],"b":[3.44, 5.96, 7.218] })

print (df.a.astype(str).str.len())
0    4
1    5
2    6
Name: a, dtype: int64

df['c'] = df.a.astype(str).str.len() - df.a.astype(int).astype(str).str.len() - 1

But because float precision is problematic count values with general data (simulate problem):

df = pd.DataFrame({"a":[2.220000000236, 3.444, 4.3726],"b":[3.44, 5.96, 7.218] })
print (df.a.astype(str).str.len())
0    14
1     5
2     6
Name: a, dtype: int64

Upvotes: 1

Rutger
Rutger

Reputation: 603

This solution creates column C with the desired result.

df['c'] = df['a'].astype(str).str.len() - df['a'].astype(int).astype(str).str.len() - 1

Upvotes: 1

Related Questions