【问题标题】:Aligning data in a single column to the right in a python DataFrame在python DataFrame中将单列中的数据向右对齐
【发布时间】:2021-12-03 20:29:00
【问题描述】:

我目前在 Python 中有一个数据框,现在我正在尝试将一列向右对齐,因为当我将其导出到 excel 时,它当前正在向左对齐。

Name Area Location Type
red 1234
green 4567 30.23mph
blue 8901

在这种情况下,我当前尝试移动的列是位置类型,它同时包含数字、字母和一些空白行。

我尝试使用这行代码:

df = df.style.set_properties(subset=["Location Type"], **{'text-align': 'right'})

我尝试在其他列上对其进行测试,以查看该列是否有问题,但我都收到了此错误。

ValueError: style is not supported for non-unique indices.

谁能告诉我我做错了什么?

提前谢谢你

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我无法让它向右对齐,所以我注意到 excel 将数字向右对齐。

    我删除了所有字符串字符并使用以下两行将列转换为浮动。

    df['Location Type'] = df['Location Type'].str.extract('(\d+\.*\d*)', expand=False)
    df['Location Type'] = df['Location Type'].astype(float)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多