【发布时间】: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