我目前在 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/