python - 不使用熊猫的python字符串操作
问题描述
如何在不使用 pandas 包的情况下使用 python 来操作这个数据集。我可以使用 pandas 来做到这一点,但这是一个新的字符串操作,我不知道该怎么做
text = """
series_id year period value footnote_codes
LASST180000000000003 1971 M01 6.6 R
LASST180000000000003 1971 M02 6.6 R
LASST180000000000003 1977 M03 6.5 R
LASST180000000000003 1976 M04 6.3 R
LASST180000000000003 1978 M05 6.0 R
LASST180000000000003 1979 M06 5.8 R
LASST180000000000003 1976 M07 5.7 R
"""
##### do not use pandas ####
### 1. replace the footnote_codes column by the month_year column
# holds a string that has the month year combination. For example, if a row has
# the month at 06 and the year at 2007,
# this column should have the following string: “06_2007”
# ### 2. only keep the data from 1976 to 1979
解决方案
我不确定您要查找的确切内容,但此代码将使用字典,键是列标题,值是列中值的列表。
它还创建脚注列。
text = """
series_id year period value footnote_codes
LASST180000000000003 1971 M01 6.6 R
LASST180000000000003 1971 M02 6.6 R
LASST180000000000003 1977 M03 6.5 R
LASST180000000000003 1976 M04 6.3 R
LASST180000000000003 1978 M05 6.0 R
LASST180000000000003 1979 M06 5.8 R
LASST180000000000003 1976 M07 5.7 R
"""
values = text.split()
headers = values[0:5]
columns = {col_name:[value for value in values[idx+5::5]] for idx, col_name in enumerate(headers[:-1])}
columns['footnotes'] = [period[1:]+'_'+year for year, period in zip(columns['year'], columns['period'])]
print(columns)
推荐阅读
- android - 无法使用 Android Studio 推送到 GitHub
- reactjs - styled-components:使用 `& + &` 选择器并根据 props 进行适配
- c++ - 我对 leetcode 72 上的递归方法不知所措
- node.js - 使用 docker-compose 将 NodeJS-App 连接到 MongoDB
- c# - 使单选按钮列表在浏览器中无需 js 即可点击,使用 asp webforms
- django - django - 如何将日期时间字段保存(更新)到数据库
- wordpress - 如何在 Google Instance VM 上启用 FTP/SFTP?
- c# - 如何在字典中排序键?
- java - 如果我更改传递给 Arrays.asList(array) 的数组,列表值会发生变化
- javascript - 通信 PC 和 Android 手机(从浏览器)并从手机到 PC 调用操作