首页 > 解决方案 > Python,使多个(点)看起来更干净

问题描述

对于一般的python或者可能只是pandas,有没有更好或更清洁的方法来做多个.(点)?例如,假设我有一个这样的代码片段:

df = pd.melt(df, id_vars='bar')
df.dropna(inplace=True)
df.drop('variable', axis=1, inplace=True)
df.reset_index(drop=True, inplace=True)
df.rename(columns={'value': 'foo'}, inplace=True)

我怎样才能让这样的东西看起来更干净?像这样:

df = pd.melt(df, id_vars='bar')
    .dropna(inplace=True)
    .drop('variable', axis=1, inplace=True)
    .reset_index(drop=True, inplace=True)
    .rename(columns={'value': 'foo'}, inplace=True)

标签: python-3.xpandas

解决方案


这完全取决于函数返回什么。该df对象具有这些方法,但这些方法返回的却没有。因此,除非您修改 Panda 的代码,否则没有严格的方法可以“使点看起来更好”。这些方法必须返回一个具有相同方法的对象,因此摆脱inplace=True参数也将修复它。None否则熊猫的回报。

本质上,inplace是修改df对象而不返回它。否则,这些方法将返回具有相同方法的对象,因此请尝试:

df = (
    pd.melt(df, id_vars='bar')
      .dropna()
      .drop('variable', axis=1)
      .reset_index(drop=True)
      .rename(columns={'value': 'foo'})
)

推荐阅读