首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在dataframe中为多列应用函数

在dataframe中为多列应用函数
EN

Stack Overflow用户
提问于 2022-05-05 07:41:03
回答 2查看 49关注 0票数 1

我有一个数据框架,如下所示,

代码语言:javascript
复制
| 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)。

以下代码中的错误

代码语言:javascript
复制
df.iloc[:, :-7] = df.iloc[:, :-7].apply(lambda x: chr(round(x / 256))
                                                        + chr(x % 256)).apply(lambda x: x[::-1])

如果我对每一列都这样做,代码就会工作。

代码语言:javascript
复制
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”列,因此很难手动输入每一列。

有没有更好的办法。

错误:

代码语言:javascript
复制
    raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'int'>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-05 07:42:23

使用DataFrame.applymap并添加到第一个lambda函数[::-1]

代码语言:javascript
复制
df.iloc[:,:-7]=df.iloc[:,:-7].applymap(lambda x: (chr(round(x / 256)) + chr(x % 256))[::-1])
print (df)
票数 1
EN

Stack Overflow用户

发布于 2022-05-05 08:12:24

以下是另一种解决方案:

代码语言:javascript
复制
selection = df.iloc[:, :-7]
df_strings = selection.floordiv(256).applymap(chr) + selection.mod(256).applymap(chr)
print(df_strings)
代码语言:javascript
复制
  190 191 192 193 194 195 196 197 198 199
0      SH  S5  XE  58        
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72123583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档