0

I’m using Python and pandas and I’m using a dataframe that has temperatures (Celsius) on it, I worked it and right now they follow this pattern, e.g.

362 370 380 385 376

I want to make it have the comma between the second and third number, e.g. 36,2 But I just can’t do this, is this possible? Thanks in advance!

2
  • 2
    If they are all numbers and not strings, wouldn't it be possible to divide everything by 10? Commented Jun 20, 2021 at 1:43
  • I was thinking on having the 0 even if they were 370, so 37.0. But yeah, that’s an alternative in case there’s no other way around it. Commented Jun 20, 2021 at 2:13

3 Answers 3

1

Try with division + astype + str.replace:

df['temp'] = (df['temp'] / 10).astype(str).str.replace('.', ',', regex=False)
   temp
0  36,2
1  37,0
2  38,0
3  38,5
4  37,6

DataFrame Used:

import pandas as pd

df = pd.DataFrame({'temp': [362, 370, 380, 385, 376]})
   temp
0   362
1   370
2   380
3   385
4   376
Sign up to request clarification or add additional context in comments.

Comments

0

Presumably, you want the last digit to be separated by a comma (for example, 88 should be 8,8). In that case, this will work:

ls = [362, 370, 380, 385, 376]
ls = [f"{str(item)[:-1]},{str(item)[-1]}" for item in ls]
# ['36,2', '37,0', '38,0', '38,5', '37,6']

Where:

  • str(item)[:-1] get's all digits except the final one
  • str(item)[-1] get's just the final digit

In a dataframe, your values are stored as a pandas series. In that case:

import pandas as pd
ls = pd.Series([362, 370, 380, 385, 376])
ls = ls.astype("str").map(lambda x : f"{x[:-1]},{x[-1]}")

Or more specifically

df["Your column"] = df["Your column"].astype("str").map(lambda x : f"{x[:-1]},{x[-1]}")

Output:

0    36,2
1    37,0
2    38,0
3    38,5
4    37,6

Comments

0

You would have to convert this integer data to string in order to enter the ','.

For example:

temp=362

x = str(temp)[:-1]+','+str(temp)[-1]

You could use this in a loop or a list comprehension which was already mentioned. (They can be trickier to understand, so I provided this instead) Hope it helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.