python - 如何从 python 数据框列中的项目列表中提取项目?

标签 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  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 循环实现这一点吗?

最佳答案

applypd.Series结合使用并重命名

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

加入到原始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

或者,提供列名称作为 index

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

关于python - 如何从 python 数据框列中的项目列表中提取项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129407/

相关文章:

python - 如何在 python 中将一个列表映射到另一个列表?

Python、py.test 和 stderr——从 Cement 日志扩展中捕获日志处理程序输出

python - Pandas 创建幂集和平均数据

java - 使用循环在每个数字之间添加空格?

python - 在Python中,如何在初始化时将类的每个新实例添加到列表中?

python - 有条件地在 pandas 中创建行

R/Python - 将字符串列拆分为多个不同的列

python - 当前实现中如何避免索引超出范围错误?

javascript - 为什么 obj 不可迭代

php - 个人网站的用户友好框架?