如何从python数据框列中的项目列表中提取项目?
我有这样一个数据帧:如何从python数据框列中的项目列表中提取项目?,python,pandas,for-loop,dataframe,Python,Pandas,For Loop,Dataframe,我有这样一个数据帧: Date sdate 0 2012-3-12 [2012, 03, 12] 1 2012-3-25 [2012, 03, 25] 2 2012-4-20 [2012, 04, 20] 3 2012-4-12 [2012, 04, 12] 4 2012-4-26 [2012, 04, 26] 我需要提取年、月和日,以像这样分开列 Date sdate year month
Date sdate
0 2012-3-12 [2012, 03, 12]
1 2012-3-25 [2012, 03, 25]
2 2012-4-20 [2012, 04, 20]
3 2012-4-12 [2012, 04, 12]
4 2012-4-26 [2012, 04, 26]
我需要提取年、月和日,以像这样分开列
Date sdate year month day
0 2012-3-12 [2012, 03, 12] 2012 03 12
1 2012-3-25 [2012, 03, 25] 2012 03 25
2 2012-4-20 [2013, 04, 20] 2013 04 20
3 2012-4-12 [2015, 06, 12] 2015 06 12
4 2012-4-26 [2011, 08, 26] 2011 08 26
我可以使用for循环实现这一点吗?使用
apply
和pd.Series
以及rename
列
In [784]: df.sdate.apply(pd.Series).rename(columns={0:'year',1:'month',2:'day'})
Out[784]:
year month day
0 2012 3 12
1 2012 3 25
2 2012 4 20
3 2012 4 12
4 2012 4 26
join
到原始df
In [785]: df.join(df.sdate.apply(pd.Series).rename(columns={0:'year',1:'month',2:'day'}))
Out[785]:
Date sdate year month day
0 2012-3-12 [2012, 3, 12] 2012 3 12
1 2012-3-25 [2012, 3, 25] 2012 3 25
2 2012-4-20 [2012, 4, 20] 2012 4 20
3 2012-4-12 [2012, 4, 12] 2012 4 12
4 2012-4-26 [2012, 4, 26] 2012 4 26
或者,提供列名称作为索引
In [786]: df.sdate.apply(lambda x: pd.Series(x, index=['year', 'month', 'day']))
Out[786]:
year month day
0 2012 3 12
1 2012 3 25
2 2012 4 20
3 2012 4 12
4 2012 4 26
我尝试了前两行代码,但在此之后,当我执行df.head()时,我没有得到新的数据帧。它仍然显示了旧的结果。您需要像
df=df.join(df.sdate.apply…
那样重新分配结果,以便将结果存储在新的df
中。我做过一次,结果显示列重叠。但现在它工作正常,我使用了jupyter notebookdf.sdate.apply(lambda x:pd.Series(x,index=['year','month','day'))这行是干什么的?你能解释一下吗?