【问题标题】:How to create a column by applying a function to the (non-trivial) index?如何通过将函数应用于(非平凡的)索引来创建列?
【发布时间】:2013-11-28 16:18:12
【问题描述】:

我可能会被这个问题否决,但到目前为止,我一直无法解决这个问题。我有一个如下所示的 DataFrame:

                                    Hits          Last visit  Bandwidth  IsWeird
Host
vocms241.cern.ch                    3777 2013-11-28 16:03:00      27554    False
ekpsquid.physik.uni-karlsruhe.de    4132 2013-11-28 14:54:00      99235     True
ec-slc6-x86-64-spi-4.cern.ch         949 2013-11-28 02:04:00    1004236    False
ec-slc6-x86-64-spi-3.cern.ch         949 2013-11-28 02:37:00    1004544    False
ec-slc6-x86-64-spi-2.cern.ch         949 2013-11-28 02:01:00    1004103    False

所以你看,DataFrame 的索引是一个字符串。现在,我有一个函数 get_something 将索引中的主机映射到另一个字符串,我想将结果添加为新列:

                                    Hits          Last visit  Bandwidth  IsWeird                NewField
Host
vocms241.cern.ch                    3777 2013-11-28 16:03:00      27554    False            STRING-0-0-1
ekpsquid.physik.uni-karlsruhe.de    4132 2013-11-28 14:54:00      99235     True  AnotherDifferentString
ec-slc6-x86-64-spi-4.cern.ch         949 2013-11-28 02:04:00    1004236    False          No_String_here
ec-slc6-x86-64-spi-3.cern.ch         949 2013-11-28 02:37:00    1004544    False                    None
ec-slc6-x86-64-spi-2.cern.ch         949 2013-11-28 02:01:00    1004103    False   I_dont-Know-what_else

我目前实现这一点的复杂方法是​​:(假设 DataFrame 是 df 并且 pandas 被导入为 pd):

_temp = pd.DataFrame(df.reset_index()['Host'])
_temp['NewField'] = _temp.Host.apply(get_something)
_temp.set_index('Host', inplace=True)
df = pd.merge(df, _temp, left_index=True, right_index=True)

但我不敢相信需要这么多代码才能实现。

【问题讨论】:

    标签: python pandas apply dataframe


    【解决方案1】:

    可能是这样的?

    df['NewField'] = pd.Series(df.index).apply(get_something)
    

    【讨论】:

    • 哦,很抱歉耽搁了这么久,感谢您的建议。我试过了,NewField 满是 NaN :(
    【解决方案2】:

    在处理了其他一些事情并多次回到这个问题之后,我决定采用一种不那么复杂的方法:

    df['NewField'] = df.index                            # Copy the contents of 
                                                         # the index to a new column.
    df['NewField'] = df['NewField'].apply(get_something) # Apply the function
    

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 1970-01-01
      • 2016-06-15
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多