【问题标题】:Combining rows in DataFrame合并DataFrame中的行
【发布时间】:2012-11-25 06:52:07
【问题描述】:

我有一个熊猫 DataFrame,它有 18 列和大约 10000 行。

我的前 3 列有 YEARMONTHDAY 的单独值。我需要合并这三列,并将所有行的整个日期放在一列中。

到目前为止我的代码是:

df.merge('Year','/','Month')

【问题讨论】:

  • 什么是DataFrame?请向我们展示一些代码,以便我们了解您在做什么。
  • 它是一个 pandas DataFrame 我确定 ... pandas 是一个具有附加功能的 numpy 包装器 ....(它可能被归类为不仅仅是一个包装器)
  • temp = read_table(folder + r'\BBE_12-11-13_0731_edited_2.lvm', sep=r'\t') cols = ['Year', 'Month', 'Day', '小时''分钟','秒','深度(m)','温度(摄氏度)','绿色(μg_l)','Blue_Green(μg_l)','硅藻(μg_l)','加密(μg_l) )', 'Class5 (µg_l)', 'Class6 (µg_l)', 'Class7 (µg_l)', '黄色 (µg_l)', '传输 (%)'] df = DataFrame(data = temp) df.columns =列
  • 已转发问题....请查看以下链接/stackoverflow.com/questions/13757490/…
  • @RahulBhatia 你为什么转发这个问题,而不是编辑它?

标签: python numpy python-3.x python-2.7 pandas


【解决方案1】:

您正在寻找apply merge 就像数据库连接。):

In [1]: from pandas import DataFrame

In [2]: df = DataFrame([[1,11,2012],[1,10,2012]], columns=['day','month','year'])

In [3]: df
Out[3]: 
   day month  year
0    1    11  2012
1    1    10  2012

In [4]: df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)
Out[4]: 
0    1/11/2012
1    1/10/2012

axis=1 部分表示您选择的是列而不是行。

如果你想给出一个具体的日期,你可以使用 datetime:

In [5]: import datetime

In [6]: df.apply(lambda row: datetime.datetime(row['year'],row['month'],row['day']), axis=1)
Out[6]: 
0    2012-11-01 00:00:00
1    2012-10-01 00:00:00

您可以将这些作为列添加到数据框中,如下所示:

In [7]: df['new_date'] = df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)

In [8]: df
Out[8]: 
   day month  year   new_date
0    1    11  2012  1/11/2012
1    1    10  2012  1/10/2012

.

值得注意的是,pandas 有一个简单的方法来parse_dates when reading as a csv

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多