Skip to main content
 首页 » 编程设计

python之如何通过将函数应用于(非平凡的)索引来创建列

2024年11月01日8cloudgamer

我可能会被这个问题否决,但到目前为止我还无法解决这个问题。我有一个看起来像这样的 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) 

但我无法相信需要那么多代码才能实现这一目标。

请您参考如下方法:

可能是这样的?

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