【问题标题】:Strings & Objects in a Column (Pandas)列中的字符串和对象(熊猫)
【发布时间】:2020-06-11 07:19:19
【问题描述】:

GitHub Link to the notebook

我目前正在开展一个项目,分析德克萨斯州奥斯汀的仇恨犯罪趋势。目前,我的数据有问题。对于“事件编号”列,我想将其分成两部分……“-”之前的数字清楚地表示年份,我想将其合并到“月”列中。 '-' 后面的数字我想保留在 'incident_number' 列中。

有谁知道我怎么能做到这一点?

最初我尝试过:

aus_final['incident_number'] = pd.to_datetime(aus_final['incident_number'], format='%d%m%Y')

产生了错误:

ValueError: time data '2017-241137' does not match format '%d%m%Y' (match)

我有点知道会发生这种情况,但无论如何我都必须尝试。 :P 不用说,我还是个 Python 新手。非常感谢任何帮助。

【问题讨论】:

  • 欢迎来到 Stackoverflow。请花时间阅读how to provide a great pandas example 上的这篇文章以及如何提供minimal, complete, and verifiable example 并相应地修改您的问题。 how to ask a good question 上的这些提示也可能有用。
  • 请注意,木星笔记本的链接无效。无论如何,最好在问题本身中包含相关数据。另外,请说明预期的输出是什么。
  • 问题正是错误所说ValueError: time data '2017-241137' does not match format '%d%m%Y' (match),即您的数据与您提供的格式不匹配,wchich 期望24112017(%d%m%Y)
  • 同意,问题是我不确定如何克服这个问题。通过重新格式化数据?我只是不确定....

标签: python pandas dataframe multiple-columns


【解决方案1】:

Link to the referenced notebook

我尝试了几次,但我终于做对了。老实说,这是一个反复试验的问题。我阅读了几个关于 stackoverflow 的问题论坛,这些论坛与 pandas 以及如何构造、格式化列等有关。 splitting columnshandling categorical dataanother aid on categorical data 仅举几例。我最终用以下代码中奖了:

new = aus_final["incident_number"].str.split("-", n = 1, expand = True)
aus_final["year"]= new[0]
aus_final["occurence_number"]= new[1]
aus_final.drop(columns =["incident_number"], inplace = True)
aus_final['date'] = aus_final[['month', 'year']].agg('-'.join, axis=1)
aus_final.drop(['month', 'occurence_number', 'year'], axis=1, inplace=True)
aus_final = aus_final[['date', 'bias', 'number_of_victims_over_18', 'offense_location']]
aus_final.rename(columns={'number_of_victims_over_18': 'victims'}, inplace=True)
aus_final['date'] = pd.to_datetime(aus_final['date'])
aus_final.set_index('date', inplace=True)

我可能学得比较慢,但是一旦我自己尝试了几次,我肯定会记住所有东西。 :) 感谢你们引导我朝着正确的方向前进!

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2019-11-23
    • 2023-01-09
    • 1970-01-01
    相关资源
    最近更新 更多