相关疑难解决方法(0)

Pandas Merge - 如何避免重复列

我正在尝试两个数据帧之间的合并.每个数据框都有两个索引级别(日期,cusip).例如,在列中,某些列匹配两者(货币,adj日期).

通过索引合并这些的最佳方法是什么,但不要取两份货币和约会日期.

每个数据框是90列,所以我试图避免手动编写所有内容.

df:                 currency  adj_date   data_col1 ...
date        cusip
2012-01-01  XSDP      USD      2012-01-03   0.45
...

df2:                currency  adj_date   data_col2 ...
date        cusip
2012-01-01  XSDP      USD      2012-01-03   0.45
...
Run Code Online (Sandbox Code Playgroud)

如果我做:

dfNew = merge(df, df2, left_index=True, right_index=True, how='outer')
Run Code Online (Sandbox Code Playgroud)

我明白了

dfNew:              currency_x  adj_date_x   data_col2 ... currency_y adj_date_y
date        cusip
2012-01-01  XSDP      USD      2012-01-03   0.45             USD         2012-01-03
Run Code Online (Sandbox Code Playgroud)

谢谢!...

python pandas

55
推荐指数
4
解决办法
8万
查看次数

pandas DataFrame concat/update("upsert")?

我正在寻找一种优雅的方法将所有行从一个DataFrame附加到另一个DataFrame(两个DataFrame具有相同的索引和列结构),但是如果两个DataFrame中都出现相同的索引值,请使用第二个数据中的行帧.

所以,例如,如果我开始:

df1:
                    A      B
    date
    '2015-10-01'  'A1'   'B1'
    '2015-10-02'  'A2'   'B2'
    '2015-10-03'  'A3'   'B3'

df2:
    date            A      B
    '2015-10-02'  'a1'   'b1'
    '2015-10-03'  'a2'   'b2'
    '2015-10-04'  'a3'   'b3'
Run Code Online (Sandbox Code Playgroud)

我希望结果如下:

                    A      B
    date
    '2015-10-01'  'A1'   'B1'
    '2015-10-02'  'a1'   'b1'
    '2015-10-03'  'a2'   'b2'
    '2015-10-04'  'a3'   'b3'
Run Code Online (Sandbox Code Playgroud)

这类似于我认为在某些SQL系统中称为"upsert"的内容---更新和插入的组合,在某种意义上,每行来自df2(a)用于更新现有行,df1如果行键已经存在于df1,或(b)df1如果行密钥尚不存在则插入到末尾.

我想出了以下内容

pd.concat([df1, df2])     # concat the two DataFrames
    .reset_index()        # turn 'date' into a regular column
    .groupby('date')      # group rows by values in the 'date' column
    .tail(1) …
Run Code Online (Sandbox Code Playgroud)

python pandas

24
推荐指数
2
解决办法
5019
查看次数

标签 统计

pandas ×2

python ×2