繁体   English   中英

python pandas dataframe 合并两行

[英]python pandas dataframe merge two rows

我正在尝试制作一个选项 T 表。 我有一个 pandas dataframe 像这样:

             name             contract   optionName      call_or_put     IV
0             Crude Oil         CL2009     CL2009C42         call       51.25%
1             Crude Oil         CL2009     CL2009P42         put        52.13%
2             Gold              GC2009     GC2009C1900       call       20%
3             Gold              GC2009     GC2009P1900       put        22%

我想把它改成这样:

      name          contract       call          IV_call       put         IV_put
0    Crude Oil       CL2009       CL2009C42       51.25%     CL2009P42      52.13%
1    Gold            GC2009       GC2009C1900      20%       GC2009P1900     22%

我正在考虑将df分离为两个数据帧,并使用combine_first 但我无法让它发挥作用。 有任何想法吗? 提前致谢。

一种方法是简单地将 dataframe 分成两个不同的 dataframe。

df = pd.DataFrame({'name': ['crude oil', 'crude oil', 'gold', 'gold'],
                     'contract': ['CL2009', 'CL2009', 'GC2009', 'GC2009'],
                     'optionName': ['CL2009C42', 'CL2009P42', 'GC2009C1900', 'GC2009P1900'],
                     'call_or_put': ['call', 'put', 'call', 'put'],
                     'IV': ['51.25%', '52.13%', '20%', '22%']},
                    index=[0, 1, 2, 3])

#dropping the duplicate i.e creating a new frame.
new1 = df.drop_duplicates(subset ="name", keep = 'last')

#creating new frame by removing the first frame from the original frame.
new2 = df.drop(new1['optionName'].index)
# final frame
final_df = pd.merge(new2 , new1, on=['name' , 'contract'])
final_df.drop(columns = ['call_or_put_x','call_or_put_y'] , inplace=True)
final_df
# you can rename column name to get your desired result.

试试这个,使用pandas.concat

import pandas as pd

print(
    pd.concat([
        df[df.call_or_put.eq("call")]
            .rename(columns={"IV": "IV_call", "optionName": "call"}).set_index("name"),
        df.loc[df.call_or_put.eq("put"), ['name', 'IV', 'optionName']]
            .rename(columns={"IV": "IV_put", "optionName": "put"}).set_index("name")
    ], axis=1)
        .drop(columns=['call_or_put']).reset_index()  # drop un-wanted column's
)

        name contract         call IV_call  IV_put          put
0  Crude Oil   CL2009    CL2009C42  51.25%  52.13%    CL2009P42
1       Gold   GC2009  GC2009C1900     20%     22%  GC2009P1900

这是一个 function 从原始数据帧中提取(仅)或调用(仅)。 'call data frame' 和 'put data frame' 与 pd.merge() 结合

def df_to_option(df, option_type):
    return (df.query('call_or_put == @option_type')
              .rename(columns = {'IV': f'IV_{option_type}',
                               'optionName': option_type})
              .drop(columns='call_or_put')
         )

pd.merge(left = df_to_option(df, 'call'),
         right = df_to_option(df, 'put'),
         how = 'inner',
         on = ['name', 'contract'],
        )

这是 pd.merge() 命令的结果:

   name        contract   call         IV_call    put          IV_put
0  Crude Oil   CL2009     CL2009C42    51.25%     CL2009P42    52.13%
1  Gold        GC2009     GC2009C1900  20%        GC2009P1900  22%

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM