python - pandas:列的长度必须与键的长度相同

标签 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

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

最佳答案

您的代码使用您提供的字典为我运行。尝试创建一个函数来单独处理 NaN 情况;我认为他们造成了您的问题。

像下面这样的基本内容:

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

关于python - pandas:列的长度必须与键的长度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43523227/

相关文章:

python - Python 中的 getter 和 setter

python - DataFrame 对象没有属性 'sort_values'

python - 如何为数据框中的列中的字符串创建规则?

python - 递归:具有分布的账户值(value)

python - 从元组列表中获取唯一元素的问题

python - 如何在Python中绘制非连续的自定义日期格式

python - 如何将我的 Python 代码组织成多个类?

python - 如何在Python中的Tkinter GUI中显示完整的文本?

python - Pandas dataframe sort_values 设置默认升序=假

python - pandas read_csv 中的编解码器问题