我有一个数据框架,如下所示,
| 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 |我尝试向所有列应用一个函数,但最后7列除外(16,36,116,156,176,200,key)。
以下代码中的错误
df.iloc[:, :-7] = df.iloc[:, :-7].apply(lambda x: chr(round(x / 256))
+ chr(x % 256)).apply(lambda x: x[::-1])如果我对每一列都这样做,代码就会工作。
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])在最后7列前面有多个列,大约为“200”列,因此很难手动输入每一列。
有没有更好的办法。
错误:
raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'int'>发布于 2022-05-05 07:42:23
使用DataFrame.applymap并添加到第一个lambda函数[::-1]
df.iloc[:,:-7]=df.iloc[:,:-7].applymap(lambda x: (chr(round(x / 256)) + chr(x % 256))[::-1])
print (df)发布于 2022-05-05 08:12:24
以下是另一种解决方案:
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 https://stackoverflow.com/questions/72123583
复制相似问题