Python 如何基于另一列和键设置dataframe中新列的值?
我有一个如下的数据集,其中包括每一场比赛的球员属性。数据集采用Pandas Dataframe格式,并按每个字符的日期降序排序Python 如何基于另一列和键设置dataframe中新列的值?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个如下的数据集,其中包括每一场比赛的球员属性。数据集采用Pandas Dataframe格式,并按每个字符的日期降序排序 characterId date kills deaths matchResult 200 3-5-2014-22:30:10 10 12 0 300 4-4-2014-23:30:10 10 13 1 400 1-2-2014-17:30:
characterId date kills deaths matchResult
200 3-5-2014-22:30:10 10 12 0
300 4-4-2014-23:30:10 10 13 1
400 1-2-2014-17:30:10 9 10 1
201 3-5-2014-22:20:05 11 16 0
301 1-4-2014-20:20:05 18 15 1
我想添加一个新列(nextResult
),其中包含上次匹配的matchResult
的值。新的数据帧应如下所示:
characterId date kills deaths matchResult nextResult
200 3-5-2014-22:30:10 10 12 0 nan
300 4-4-2014-23:30:10 10 13 1 0
400 1-2-2014-17:30:10 9 10 1 1
201 3-5-2014-22:20:05 11 16 0 nan
301 1-4-2014-20:20:05 18 15 1 0
您可以使用
shift
和where
检查字符是否已重新启动
df['nextResult'] = df.shift(1)['matchResult'].where(df.characterid.diff().fillna(0).ge(0))
输出:
characterid date kills deaths matchResult nextResult
0 200 3-5-2014-22:30:10 10 12 0 NaN
1 300 4-4-2014-23:30:10 10 13 1 0.0
2 400 1-2-2014-17:30:10 9 10 1 1.0
3 201 3-5-2014-22:20:05 11 16 0 NaN
4 301 1-4-2014-20:20:05 18 15 1 0.0
只需像访问字典一样访问数据帧:
import numpy as np # for np.NaN (or use NaN = float('nan'))
df = pd.DataFrame({ ... }) # your dataframe possibly from a CSV
df['nextResult'] = [np.NaN, 0, 1, np.NaN, 0]
有关pandas的介绍,请参见Scott显然有更多关于如何创建“nextResult”的信息。感谢您提供的解决方案。我尝试了它,但它显示了以下错误:`features.shift(1)['matchResult'].where(features.characterId.diff().fillna(0.ge(0))文件“C:\ProgramData\Anaconda2\lib\site packages\pandas\core\series.py”,第1459行,在diff result=algos.diff(\u values\u from\u object(self),periods)文件中“C:\ProgramData\Anaconda2\lib\site packages\pandas\core\algorithms.py”,第1251行,in-diff-out\u-arr[res\u-indexer]=arr[res\u-indexer]-arr[lag\u-indexer]类型错误:不支持的操作数类型对于-:'str'和'str'`您是CharacterId始终是整数还是其中可能有一些字母?
CharacterId
是字符串。是的,diff不能很好地处理字符串。我们可以使用CharacterId.astype(int).diff()如果在characterid中不需要数字以外的任何内容,则输出总是nan。characterid
是19位字符串格式,例如“2305843009218992152”。
import numpy as np # for np.NaN (or use NaN = float('nan'))
df = pd.DataFrame({ ... }) # your dataframe possibly from a CSV
df['nextResult'] = [np.NaN, 0, 1, np.NaN, 0]