user_v27
user_v27

Reputation: 423

Convert Data format in python to ascii

Data from Allen Bradley PLC comes in the format of 5 digit numbers in column 'value'

| tagid | value | datetime                | quality |
|-------|-------|-------------------------|---------|
| T0    | 21328 | 05-03-2021 14:11:53.087 | 192     |
| T1    | 12340 | 05-03-2021 14:14:25.787 | 192     |
| T2    | 17992 | 05-03-2021 14:16:52.687 | 192     |
| T0    | 17992 | 05-03-2021 14:19:14.470 | 192     |
| T1    | 17992 | 05-03-2021 14:21:31.623 | 192     |
| T2    | 21328 | 05-03-2021 14:23:50.220 | 192     |
| T0    | 21328 | 05-03-2021 14:26:13.747 | 192     |
| T1    | 17992 | 05-03-2021 14:28:29.817 | 192     |
| T2    | 17992 | 05-03-2021 14:31:03.603 | 192     |

Initially was i not able to recognize the steps to fetch desired value from this 5 digit value.

Then after some experiments in Excel/Python I did following steps and got the correct desired value

Steps:
Step 1. Divide value by 256 and round (Eg 17992/256 which is 70
Step 2. Do Mod the same value (Eg: =Mod(17992,256) which is 72
Step 3. Find Ascii value equitant to 70, which is F
Step 4. Find Ascii value equitant to 72, which is H
Step 5: Concatenate F& H which is FH

So the desired value for say 17992 is 'FH' , 12340 is '0468'

| tagid | value | datetime                | quality |
|-------|-------|-------------------------|---------|
| T0    | FH    | 05-03-2021 14:11:53.087 | 192     |
| T1    | 02    | 05-03-2021 14:14:25.787 | 192     |

Is there any simple and efficient method in python data frame to do above steps, instead of doing step by step

Upvotes: 1

Views: 235

Answers (2)

arhr
arhr

Reputation: 1591

You can use the apply method to apply a function throughout a DataFrame (or Series).

df['value_converted'] = df['value'].apply(lambda x: chr(round(x / 256)) + chr(x % 256))

Upvotes: 2

Rob Raymond
Rob Raymond

Reputation: 31226

  • simple integer div and mod
  • apply() to series to get ASCII code
df.value = (df.value//256).apply(chr) + (df.value%256).apply(chr)

tagid value datetime quality
0 T0 SP 05-03-2021 14:11:53.087 192
1 T1 04 05-03-2021 14:14:25.787 192
2 T2 FH 05-03-2021 14:16:52.687 192
3 T0 FH 05-03-2021 14:19:14.470 192
4 T1 FH 05-03-2021 14:21:31.623 192
5 T2 SP 05-03-2021 14:23:50.220 192
6 T0 SP 05-03-2021 14:26:13.747 192
7 T1 FH 05-03-2021 14:28:29.817 192
8 T2 FH 05-03-2021 14:31:03.603 192

Upvotes: 2

Related Questions