I have the following df and i would like to convert each ip address into a string ie "207.46.13.187"
I have tried the following, but it didn't work. I am not sure if the decimals have anything to do with it.
df['IP'] = df['IP'].astype(str)
current dataframe:
IP date year month
0 207.46.13.187 24 2020 6
1 207.46.13.187 24 2020 6
2 40.77.167.144 24 2020 6
3 40.77.167.144 24 2020 6
4 207.46.13.146 23 2020 6
... ... ... ... ...
4512 82.145.221.171 14 2015 5
4513 82.145.209.120 13 2015 5
4514 82.145.221.232 13 2015 5
4515 82.145.221.232 13 2015 5
4516 82.145.222.238 13 2015 5
Goal:
IP date year month
0 "207.46.13.187" 24 2020 6
1 "207.46.13.187" 24 2020 6
2 "40.77.167.144" 24 2020 6
3 "40.77.167.144" 24 2020 6
4 "207.46.13.146" 23 2020 6
Thank you!
Try using:
df['IP'] = df['IP'].apply(lambda x: str(x))
Below is a quick example I have compiled. I will be looking at whole integers only, but hopefully this clarifies some confusion with data types in Pandas.
I will create a dataframe
df = pd.DataFrame({'IP': [1, 2, 3, 4, 5]})
Let's check the type, it should return integers:
df.dtypes
IP int64
dtype: object
Let's check this with a list
df['IP'].values.tolist()
[1, 2, 3, 4, 5] # we have a list of integers!
Now, let's convert it to a string:
df['IP'] = df['IP'].apply(lambda x: str(x))
Let's check the type again, it should return object :
df.dtypes
IP object
dtype: object
Let's check this with a list again:
df['IP'].values.tolist()
['1', '2', '3', '4', '5']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.