python - 在 utf8 中迭代两个数据帧的列和 str.encode

标签 python pandas loops unicode encode

我目前在 Python 2.7 上运行,并且有两个数据帧 x 和 y。我想使用某种列表理解来遍历两列,并在每一列上使用 str.encode('UTF8) 来摆脱 unicode。

这工作得很好并且易于阅读,但想尝试使用更快更高效的东西。

for col in y:
  if y[col].dtype=='O':
    y[col] = y[col].str.encode("utf-8")

for col in x:
  if x[col].dtype=='O':
    x[col] = x[col].str.encode("utf-8")

我尝试过的其他方法:

1.)[y[col].str.encode("utf-8") for col in y if y[col].dtype=='O' ]

2.)y.columns= [( y[col].str.encode("utf-8") if y[col].dtype=='O' else y[col]) for col in y ]

3.)y.apply(lambda x : (y[col].str.encode("utf-8") for col in y if y[col].dtype=='O'))

我收到 2.) 和 3.) 的值错误和长度不匹配错误

最佳答案

您可以使用select_dtypes 获取对象列,然后对每一列调用apply 对其进行编码:

u = df.select_dtypes(include=[object])
df[u.columns] = u.apply(lambda x: x.str.encode('utf-8'))

编写一个小函数来执行此操作并为每个数据帧调用它。

def encode_df(df):
    u = df.select_dtypes(include=[object])
    df[u.columns] = u.apply(lambda x: x.str.encode('utf-8'))
    return df

x, y = encode_df(x), encode_df(y)

关于python - 在 utf8 中迭代两个数据帧的列和 str.encode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562917/

相关文章:

Python 每 5 分钟重复一次算法

python - 在类内分配给 Pandas DataFrame 会出现 TypeError

python - 使用 pandas 对列中的重复值进行分类

PHPExcel 导出到 Codeigniter 循环数据数组中的 excel

python - pickling python 对象到谷歌云存储

python - 根据最高分选择最佳值(value)

python - for 循环的下一个抽象级别?

python - 使用 POSIX 排除字符串中的单词

Python:如何根据程度为网络节点着色?

python - 如何获取检测到的物体的类别 - tensorflow