【问题标题】:How to convert 2 DataFrame columns to ascii?如何将 2 个 DataFrame 列转换为 ascii?
【发布时间】:2018-02-26 22:52:18
【问题描述】:

我有一个包含 2 列字符串的 DataFrame,从 tsv 文件导入。两列都需要转换为ascii。 (这是因为我想通过 scikit-learn 中的 CountVectorizer 和 TfidfTransformer 管道传递文本。

我在 stackoverflow 和外部都浏览了几十个帖子,但无法弄清楚这一点。我的代码如下,包括我尝试过的一些东西。

有什么建议可以完成这项工作吗?

# tried including adding encoding="utf-8", does not work
df = pd.read_csv(questions, usecols = [3, 4, 5], nrows = 10, header=0, sep="\t") 

y = df["is_duplicate"].values
X = df.drop("is_duplicate", axis=1).values

for col in X:
    X = X.encode('utf-8') # does not work

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3,
random_state = 21, stratify = y)

def flat_list(my_list):
    return [str(item) for sublist in my_list for item in sublist]

def transform_data(trans_obj_list,dataset_splits):
    X_train = dataset_splits[0].astype(str)

X_train = flat_list(X_train)

for trfs in trans_obj_list:
    transformed_vector = trfs().fit(X_train)
    for x in range(0,len(dataset_splits)):
        dataset_splits[x] =flat_list(dataset_splits[x].astype(str))

return dataset_splits

new_X_train, new_X_test = transform_data([CountVectorizer,TfidfTransformer],
[X_train, X_test])

【问题讨论】:

  • 否则请检查我的答案,您能否分享您的数据样本?

标签: python-3.x pandas numpy ascii


【解决方案1】:

您需要像这样调用X.str.encode(..) 而不是X.encode(..)

for col in X:
    X = X.str.encode('utf-8') # does not work

【讨论】:

    【解决方案2】:

    我在这个问题中找到了我的问题的答案:How do I use encode (Python 3) to fix non-ascii code for CSV import in Pandas?

    file_obj = open(file_name, encoding="utf-8")
    master = pd.read_csv(file_obj)
    

    我只是使用“ascii”而不是“utf-8”。

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2015-08-08
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      相关资源
      最近更新 更多