Home > database >  pandas apply() auto add .0 behind of my string
pandas apply() auto add .0 behind of my string

Time:01-06

I am still learning python and new to using panda module. I am trying to combine two columns in a csv consist of IP address and CIDR and output to a text file as e.g: 10.0.0.1/24 and below is my code:

import pandas as pd

path = '/Users/myfolder/Downloads/ip.csv'
df = pd.read_csv(path)
df = df[['Address', 'CIDR']].apply(lambda x: '/'.join(x.map(str)), axis=1)
df.to_csv("/Users/myfolder/Downloads/result.txt", header=False, index=False)

However, the result has a .0 behind of each line:

10.0.0.1/24.0 10.0.0.2/24.0 10.0.0.3/24.0 is there a flag to enable or is there something wrong in the code section that i need to change?

Tried using other concatenate method like merge() or agg() but seems like join() and map() are the closest i can get as the data are not string to begin with.

CodePudding user response:

You should first convert to integer, then to string to avoid having floats:

out = (df[['Address', 'CIDR']]
      .astype({'CIDR': 'Int64'})
      .apply(lambda x: '/'.join(x.map(str)), axis=1)
      )

original answer

lambda x: '/'.join(x.astype(int).astype(str))

Or, if you have NaNs:

lambda x: '/'.join(x.astype('Int64').astype(str))
  • Related