pandas:列的长度必须与key相同

时间:2017-04-20 15:02:50

标签: python pandas

我试图将几个列重新格式化为字符串(它们包含NaN,所以我不能只是以整数形式读取它们)。所有列目前都是float64,我想让它们不会有小数。

以下是数据:

{'crash_id': {0: 201226857.0,
  1: 201226857.0,
  2: 2012272611.0,
  3: 2012272611.0,
  4: 2012298998.0},
 'driver_action1': {0: 1.0, 1: 1.0, 2: 29.0, 3: 1.0, 4: 3.0},
 'driver_action2': {0: 99.0, 1: 99.0, 2: 1.0, 3: 99.0, 4: 99.0},
 'driver_action3': {0: 99.0, 1: 99.0, 2: 99.0, 3: 99.0, 4: 99.0},
 'driver_action4': {0: 99.0, 1: 99.0, 2: 99.0, 3: 99.0, 4: 99.0},
 'harmful_event1': {0: 14.0, 1: 14.0, 2: 14.0, 3: 14.0, 4: 14.0},
 'harmful_event2': {0: 99.0, 1: 99.0, 2: 99.0, 3: 99.0, 4: 99.0},
 'harmful_event3': {0: 99.0, 1: 99.0, 2: 99.0, 3: 99.0, 4: 99.0},
 'harmful_event4': {0: 99.0, 1: 99.0, 2: 99.0, 3: 99.0, 4: 99.0},
 'most_damaged_area': {0: 14.0, 1: 2.0, 2: 14.0, 3: 14.0, 4: 3.0},
 'most_harmful_event': {0: 14.0, 1: 14.0, 2: 14.0, 3: 14.0, 4: 14.0},
 'point_of_impact': {0: 15.0, 1: 1.0, 2: 14.0, 3: 14.0, 4: 1.0},
 'vehicle_id': {0: 20121.0, 1: 20122.0, 2: 20123.0, 3: 20124.0, 4: 20125.0},
 'vehicle_maneuver': {0: 3.0, 1: 1.0, 2: 4.0, 3: 1.0, 4: 1.0}}

当我尝试将这些列转换为字符串时,会发生以下情况:

>> df[['crash_id','vehicle_id','point_of_impact','most_damaged_area','most_harmful_event','vehicle_maneuver','harmful_event1','harmful_event2','harmful_event3','harmful_event4','driver_action1','driver_action2','driver_action3','driver_action4']] = df[['crash_id','vehicle_id','point_of_impact','most_damaged_area','most_harmful_event','vehicle_maneuver','harmful_event1','harmful_event2','harmful_event3','harmful_event4','driver_action1','driver_action2','driver_action3','driver_action4']].applymap(lambda x: '{:.0f}'.format(x))

File "C:\Users\<name>\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2376, in _setitem_array
        raise ValueError('Columns must be same length as key')

ValueError: Columns must be same length as key

我之前从未见过这个错误,觉得这很简单......我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的代码会使用您提供的字典为我运行。尝试创建一个单独处理NaN案例的函数;我认为他们正在引发你的问题。

如下所示的基本内容:

def formatter(x):
    if x == None:
        return None
    else:
        return '{:.0f}'.format(x)