【问题标题】:Convert integer to string type when retrieving values from a pandas dataframe从熊猫数据框中检索值时将整数转换为字符串类型
【发布时间】:2017-08-24 15:22:54
【问题描述】:

我正在尝试从使用 Pandas 生成的列表中转换数据输出(从整数到字符串)。

我从 csv 文件中得到了数据的输出。

这是我的代码,涵盖了使用 Pandas 的表达式(不包括显示如何生成对象“InFile”(csv 文件)的部分)。

import pandas as pd
....

with open(InFile) as fp:
     skip = next(it.ifilter(
        lambda x: x[1].startswith('ID'),
        enumerate(fp)
     ))[0]

dg = pd.read_csv(InFile, usercols=['ID'], skiprows=skip)
dgl = dg['ID'].values.tolist()

目前,输出是一个列表(下面的示例)。

 [111111, 2222, 3333333, 444444] 

我正在尝试匹配其他 List 中的数据(填充到 String 或 Varchar(MySQL 中的数据类型)中,但不知何故,我无法找到任何匹配项。我以前的帖子 -> How to find match from two Lists (from MySQL and csv)

所以,我猜测 Pandas 生成的 List 中的数据类型是 Integer

那么,如何将数据类型从 Integer 转换为 String?

例如,我应该在哪一行添加类似 str(10) 的内容?

【问题讨论】:

  • 您想将ID 转换为字符串吗?
  • ID 只是列的名称。
  • 是的,我明白了。

标签: python pandas dataframe type-conversion


【解决方案1】:

你可以使用pd.Series.astype:

dgl = dg['ID'].astype(str).values.tolist()
print(dgl)

输出:

['111111', '2222', '3333333', '444444']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多