我试图解决我的问题好几个小时,但不知怎的,我没有得到正确的解决方案。 我有一个pandas数据框,其中包含一列日期,而这些日期又作为每行的列表存储。
df['date']=pd.to_datetime(df["date"])
给我错误:不可用的类型:'list'
我的数据框如下所示:
0 [February 28, 2013 Thursday]
1 [November 2, 2012 Friday]
2 [July 31, 2012 Tuesday]
3 [May 10, 2012 Thursday]
4 [June 23, 2004 Wednesday]
因此,每一行都是一个列表,但每个列表只包含一个字符串。我想将每行中的这一个字符串转换为数据帧中的日期时间格式(就像02-28-2013),以便我可以执行日期操作。
如何以能够执行pd.to_datetime命令的方式转换列?
非常感谢!!
答案 0 :(得分:1)
我创建我的DataFrame:
Option Explicit
' The following code adapted from: https://stackoverflow.com/questions/13465709/repeating-microsoft-word-vba-until-no-search-results-found
Sub SearchFN()
Dim iCount As Integer
Dim lStart As Long
'Always start at the top of the document
Selection.HomeKey Unit:=wdStory
'find a footnote to kick it off
With Selection.Find
.ClearFormatting
.Text = "[nm]>"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchFuzzy = False
.MatchWildcards = True
.Execute
End With
'Jump back to the start of the document.
Selection.HomeKey Unit:=wdStory
'If we find one then we can set off a loop to keep checking
'I always put a counter in to avoid endless loops for one reason or another
Do While Selection.Find.Found = True And iCount < 2000
iCount = iCount + 1
Selection.Find.Execute
'On the last loop you'll not find a result so check here
If Selection.Find.Found Then
' Exit if we start back at the beginning
If Selection.Start < lStart Then
Exit Do
End If
'Reset the find parameters
With Selection.Find
.ClearFormatting
.Text = "[nm]>"
If Selection.Text = "m" Then
Debug.Print "found 'm' at position: " & Selection.Start
Selection.Text = "n"
ElseIf Selection.Text = "n" Then
Debug.Print "found 'n' at position: " & Selection.Start
Selection.Text = "m"
End If
lStart = Selection.Start
' .Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchFuzzy = False
.MatchWildcards = True
End With
End If
Loop
End Sub
我曾经写过一些随机日期,但它也是带有列表的大熊猫。
import pandas as pd
df = pd.DataFrame(columns=['date'])
df['date']=pd.to_datetime(df["date"])
df.date=[['01-01-2013'], ['2-2-2015'], ['July 31, 2012']]
您必须访问列表中的元素,因此只需使用 lambda函数
>>> df.date
0 [01-01-2013]
1 [2-2-2015]
2 [July 31, 2012]