【发布时间】:2018-11-19 11:39:49
【问题描述】:
我有一个正在尝试清理的电影 CSV 文件。我正在使用 Jupyter 笔记本。
它有 10,000 行和 5 列。以下是一些示例数据:
Movie Name | Genre | Date Released | Length | Rating |
The Godfather | Crime | March 24, 1972 | 175 | R |
The Avengers | Action | May 5, 2012 | 143 | PG-13 |
The Dark Knight | Action | Crime | July 18, 2008 | 152 | PG-13
请注意,对于“黑暗骑士”,由于有 2 个类型,因此行会向右移动。我想清理数据,使该行变为:
The Dark Knight | Action, Crime | July 18, 2008 | 152 | PG-13
我所做的是(在 Jupyter 笔记本中)
import pandas as pd
path = 'movies.csv'
df = pd.read_csv(path, header=0, names=['Movie Name', 'Genre', 'Date Released','Length','Rating','Extra'])
ctrCheck = 0
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
while ctrCheck < len(df.index):
check = str(df['Date Released'][ctrCheck])
if any(month in check for month in months):
replaceStr = df.loc[ctrCheck, 'Genre'] + "," + df.loc[ctrCheck, 'Date Released']
df.loc[ctrCheck, 'Genres'] = replaceStr
df.loc[ctrCheck, 'Date Released'] = df.loc[ctrCheck, 'Length']
df.loc[ctrCheck, 'Length'] = df.loc[ctrCheck, 'Rating']
df.loc[ctrCheck, 'Rating'] = df.loc[ctrCheck, 'Extra']
ctrCheck = ctrCheck + 1
df.drop(labels='Extra', inplace=True, axis='columns')
除了遍历 10,000 行之外,还有更好的方法吗?
谢谢!
【问题讨论】:
-
不是你问题的答案,但你可以写你的测试
if any(month in check for month in ['January', 'February', ...]): -
啊,好建议!会这样做:)
-
您能否提供您正在使用的实际 csv 输入,而不是问题的格式化视图?我确信应该支持 csv 读取格式来读取列表。