I have a data frame as below with multiple columns,
| 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 16 | 36 | 116 | 156 | 176 | 200 | key |
|-----|-----|-------|-------|-------|-------|-----|-----|-----|-----|----|----|-----|-----|-----|------|--------------|
| 0 | 0 | 21320 | 21301 | 22597 | 13624 | 2 | 0 | 0 | 1 | 1 | 0 | 1 | 4 | 3 | 1315 | 202205041315 |
I tried to apply a function to all columns ,other than last 7 columns (16,36,116,156,176,200,key).
Error in below code
df.iloc[:, :-7] = df.iloc[:, :-7].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
If i do it for each column, the code works
df['190] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
df['191] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
df['192] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
df['193] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
df['194] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
...
...
df['199] = df['190].apply(lambda x: chr(round(x / 256))
chr(x % 256)).apply(lambda x: x[::-1])
I have multiple columns approx '200' columns in front of last 7 columns, so its difficult to manually enter for each columns
Could there be better way to do it.
Error:
raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'int'>
CodePudding user response:
Use DataFrame.applymap
and add to first lambda function [::-1]
:
df.iloc[:,:-7]=df.iloc[:,:-7].applymap(lambda x: (chr(round(x / 256)) chr(x % 256))[::-1])
print (df)
CodePudding user response:
Here's an alternative solution:
selection = df.iloc[:, :-7]
df_strings = selection.floordiv(256).applymap(chr) selection.mod(256).applymap(chr)
print(df_strings)
190 191 192 193 194 195 196 197 198 199
0 SH S5 XE 58