这是 csv 文件中的“播出”列:作为
链接到 csv 文件:https : //drive.google.com/file/d/1w7kIJ5O6XIStiimowC5TLsOCUEJxuy6x/view? usp =sharing
我想从“from”单词后面的日期中提取日期和月份(以单词为单位),并将其存储在另一个 csv 文件的单独列中。'from' 是一个障碍,因为如果它只是作为时间戳格式很容易提取的日期。
您从一个字符串开始,并希望分解其中的数据。单引号表明这是一个字符串形式的 dict 结构。Python 标准库包括ast
(Abstract Syntax Trees) 模块,该模块的literal_eval
方法可以将字符串读入 dict,从这个 SO 答案中收集:Convert a String representation of a Dictionary to a dictionary?
您希望将apply
其添加到您的列中以获取 dict,此时您可以使用 将其扩展为单独的列.apply(pd.Series)
,基于此 SO 答案:将 Pandas 列中的字典/列表拆分为单独的列
尝试以下
import pandas as pd
import ast
df = pd.read_csv('AnimeList.csv')
# turn the pd.Series of strings into a pd.Series of dicts
aired_dict = df['aired'].apply(ast.literal_eval)
# turn the pd.Series of dicts into a pd.Series of pd.Series objects
aired_df = aired_dict.apply(pd.Series)
# pandas automatically translates that into a pd.DataFrame
# concatenate the remainder of the dataframe with the new data
df_aired = pd.concat([df.drop(['aired'], axis=1), aired_df], axis=1)
# convert the date strings to datetime values
df_aired['aired_from'] = pd.to_datetime(df_aired['from'])
df_aired['aired_to'] = pd.to_datetime(df_aired['to'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句