Группировка и агрегирование по нескольким столбцам при применении столбца в качестве аргумента агрегирования в Pandas?

Возможно, это может помочь: бесконечная структура данных JAXB, рекурсивное связывание?

@XmlAccessorType(XmlAccessType.FIELD) // add this to avoid FIELD/METHOD conflicts
public class Item {
    private int id;
    private String name;

    @XmlElement(name="item")//There is no need for XmlElementRef 
    private List items = new ArrayList();

    @XmlAttribute(name = "identifier", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String identifier;
    @XmlAttribute(name = "identifierref", required = false)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NCName")
    protected String identifierref;
    @XmlAttribute(name = "isvisible", required = false)
    protected boolean isvisible; 

    //I think here is accessors
    List[Items] getItems ...


}

0
задан Bython 23 February 2019 в 14:42
поделиться

1 ответ

Вы можете использовать пользовательскую функцию с помощью GroupBy.apply с next и iter для получения первого значения, а при отсутствии совпадения получите NaN с:

def f(x):
    c = next(iter(x.loc[x.Type == "call", 'Price']),np.nan)
    p = next(iter(x.loc[x.Type == "put", 'Price']),np.nan) 
    x['new']= c - p + x.Strike
    return x

df = df.groupby(["Expiration","Strike"]).apply(f)
print (df)

   Type       Price  Expiration  Strike         new
0   put  145.000000  2021-01-15   420.0         NaN
1  call   15.370001  2018-11-30   262.0  275.875001
2   put    1.495000  2018-11-30   262.0  275.875001
3  call   14.930000  2018-11-30   262.5         NaN

Другой решение:

#if possible `call` and `put` are not unique per groups
c = df[df.Type == "call"].groupby(["Expiration","Strike"])['Price'].first()
p = df[df.Type == "put"].groupby(["Expiration","Strike"])['Price'].first()

#if `call` and `put` are unique per groups
#c = df[df.Type == "call"].set_index(["Expiration","Strike"])['Price']
#p = df[df.Type == "put"].set_index(["Expiration","Strike"])['Price']

df1 = df.join((c - p).rename('new'), on=["Expiration","Strike"])
df1['new'] += df1['Strike']
print (df1)
   Type       Price  Expiration  Strike         new
0   put  145.000000  2021-01-15   420.0         NaN
1  call   15.370001  2018-11-30   262.0  275.875001
2   put    1.495000  2018-11-30   262.0  275.875001
3  call   14.930000  2018-11-30   262.5         NaN
0
ответ дан jezrael 23 February 2019 в 14:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: