【问题标题】:How to slice rows from two pandas dataframes then merge them with some other value如何从两个熊猫数据帧中分割行,然后将它们与其他值合并
【发布时间】:2019-01-17 17:27:09
【问题描述】:

我有两个 pandas 数据框和两个索引,以及一个日期时间变量。我想做的是:

  1. 使用索引对数据帧进行切片,然后得到两行。

  2. 将两行合并为一行。

  3. 将变量添加到行中。

  4. 然后我可以获取新的索引和日期时间值来形成更多的行,并将这些行组合成一个新的数据帧。

例子:

df1:

    A   B
0   0   10
1   1   11
2   2   12
3   3   13
4   4   14
5   5   15
6   6   16
7   7   17
8   8   18
9   9   19

df2:

    C   D
0   10  110
1   11  111
2   12  112
3   13  113
4   14  114
5   15  115
6   16  116
7   17  117
8   18  118
9   19  119

索引:3、5,日期时间:datetime.datetime(2018, 8, 10, 16, 53, 52, 760014)

输出:

    A   B   C   D   time
0   3   13  15  115 20180810-16:53:52:760014
... # More rows when there's more indexes and datetimes

【问题讨论】:

  • 这个df2有什么用?
  • 嗨,krishna,列 C 和 D 是通过索引 5 从 df2 中提取的。这有点误导,我将编辑示例

标签: python pandas dataframe


【解决方案1】:

你可以试试:

index = [3,5]
data = np.r_[df1.iloc[index[0]].values,df2.iloc[index[1]].values]
df = pd.DataFrame([data],columns = list('ABCD'))
dt = datetime.datetime(2018, 8, 10, 16, 53, 52, 760014)
df['date'] = dt

输出:

    A   B   C   D   date
0   3   13  15  115 2018-08-10 16:53:52.760014

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2014-03-01
    • 2019-07-20
    • 1970-01-01
    • 2017-10-21
    • 2020-04-05
    • 2014-12-04
    相关资源
    最近更新 更多