【问题标题】:Setting column types while reading csv with pandas使用 pandas 读取 csv 时设置列类型
【发布时间】:2016-07-11 18:23:01
【问题描述】:

尝试使用以下格式将 csv 文件读入 pandas 数据框

dp = pd.read_csv('products.csv', header = 0,  dtype = {'name': str,'review': str,
                                                      'rating': int,'word_count': dict}, engine = 'c')
print dp.shape
for col in dp.columns:
    print 'column', col,':', type(col[0])
print type(dp['rating'][0])
dp.head(3)

这是输出:

(183531, 4)
column name : <type 'str'>
column review : <type 'str'>
column rating : <type 'str'>
column word_count : <type 'str'>
<type 'numpy.int64'>

我可以理解 pandas 可能会发现很难将字典的字符串表示形式转换为给定 thisthis 的字典。但是“评分”列的内容怎么可能同时是str和numpy.int64???

顺便说一句,诸如不指定引擎或标头之类的调整不会改变任何东西。

感谢和问候

【问题讨论】:

    标签: python csv dictionary pandas types


    【解决方案1】:

    在你的循环中你正在做:

    for col in dp.columns:
        print 'column', col,':', type(col[0])
    

    并且您在任何地方都正确地将str 视为输出,因为col[0] 是列名称的第一个字母,它是一个字符串。

    例如,如果你运行这个循环:

    for col in dp.columns:
        print 'column', col,':', col[0]
    

    你会看到每个列名的字符串的第一个字母被打印出来——这就是col[0]

    您的循环仅在列名上迭代,而不是在系列数据上迭代。

    您真正想要的是在循环中检查每列数据的类型(不是其标题或部分标题)。

    所以改为获取列数据的类型(非标题数据):

    for col in dp.columns:
        print 'column', col,':', type(dp[col][0])
    

    这与您在单独打印rating 列的类型时所做的类似。

    【讨论】:

    • 谢谢,这是我的失误 :) 我选择这个作为接受的答案,因为它是对我的问题的直接回应。
    • 我猜这是一个错字,有时在专注于代码时很难检测到;)
    【解决方案2】:

    只需将read_table"," 分隔符与literal_eval 一起用作转换相关列中值的函数即可。

    recipes = pd.read_table("\\souravD\\PP_recipes.csv", sep=r',',
                          names=["id", "i", "name_tokens", "ingredient_tokens", "steps_tokens", "techniques","calorie_level","ingredient_ids"],
                          converters = {'name_tokens' : literal_eval,
                                        'ingredient_tokens' : literal_eval,
                                        'steps_tokens' : literal_eval,
                                        'techniques' : literal_eval,
                                        'ingredient_ids' : literal_eval},header=0)
    

    【讨论】:

      【解决方案3】:

      用途:

      dp.info()
      

      查看列的数据类型。 dp.columns 指的是列标题名称,是字符串。

      【讨论】:

      • 在非常密集的 pandas 文档中我错过了另一个快捷方式——谢谢。
      【解决方案4】:

      我认为你应该先检查这个:Pandas: change data type of columns

      当 google pandas dataframe column type 时,它在前 5 个答案中。

      【讨论】:

      • 谢谢,这很有用。我希望也能讨论如何强制转换为 dict 类型(如果有的话)。
      • 我不认为这是这个问题的答案 - 这个问题需要在 read_csv 过程中设置列类型期间。在给定的用例中,事后进行可能是非常不可取的。不过链接很好。
      猜你喜欢
      • 2021-08-25
      • 2014-03-26
      • 1970-01-01
      • 2020-03-27
      • 2022-10-13
      • 1970-01-01
      • 2021-12-06
      • 2021-11-08
      • 2019-12-21
      相关资源
      最近更新 更多