Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 根据条件在新列中添加值_Pandas_Python 3.5 - Fatal编程技术网

Pandas 根据条件在新列中添加值

Pandas 根据条件在新列中添加值,pandas,python-3.5,Pandas,Python 3.5,我有一个数据帧df: df = pd.DataFrame({ 'id': ['1', '1', '2', '3', '3', '8','4', '1', '2', '4'], 'start': ['2017-01-02', '2017-02-01', '2017-03-01', '2017-02-01', '2017-03-01', '2017-04-01', '2017-01-01', '2017-04-01', '2017-05-01', '2017-02-01'] })

我有一个数据帧df:

df = pd.DataFrame({
    'id': ['1', '1', '2', '3', '3', '8','4', '1', '2', '4'],
    'start': ['2017-01-02', '2017-02-01', '2017-03-01', '2017-02-01', '2017-03-01', '2017-04-01', '2017-01-01', '2017-04-01', '2017-05-01', '2017-02-01']
})

df.sort_values(['id', 'start'])
我想看看是否每个id都有第二行。如果它存在,我想添加一个新列,比如num_count,我想在其中添加整数1。如果每个id只存在一行或id的最后一行,我想添加0。 这是我想要的输出

  id num_count       start
0  1         1  2017-01-02
1  1         1  2017-02-01
7  1         0  2017-04-01
2  2         1  2017-03-01
8  2         0  2017-05-01
3  3         1  2017-02-01
4  3         0  2017-03-01
6  4         1  2017-01-01
9  4         0  2017-02-01
5  8         0  2017-04-01

我如何才能做到这一点?

您需要分配.sort\u值的结果。。如果要处理已排序的数据帧:

df = df.sort_values(['id', 'start'])
然后,这将为样本输入生成:

>>> df
  id       start
0  1  2017-01-02
1  1  2017-02-01
7  1  2017-04-01
2  2  2017-03-01
8  2  2017-05-01
3  3  2017-02-01
4  3  2017-03-01
6  4  2017-01-01
9  4  2017-02-01
5  8  2017-04-01
>>> df['num_count'] = df['id'].duplicated('last').astype(int)
>>> df
  id       start  num_count
0  1  2017-01-02          1
1  1  2017-02-01          1
7  1  2017-04-01          0
2  2  2017-03-01          1
8  2  2017-05-01          0
3  3  2017-02-01          1
4  3  2017-03-01          0
6  4  2017-01-01          1
9  4  2017-02-01          0
5  8  2017-04-01          0

您需要分配.sort_值的结果。。如果要处理已排序的数据帧:

df = df.sort_values(['id', 'start'])
然后,这将为样本输入生成:

>>> df
  id       start
0  1  2017-01-02
1  1  2017-02-01
7  1  2017-04-01
2  2  2017-03-01
8  2  2017-05-01
3  3  2017-02-01
4  3  2017-03-01
6  4  2017-01-01
9  4  2017-02-01
5  8  2017-04-01
>>> df['num_count'] = df['id'].duplicated('last').astype(int)
>>> df
  id       start  num_count
0  1  2017-01-02          1
1  1  2017-02-01          1
7  1  2017-04-01          0
2  2  2017-03-01          1
8  2  2017-05-01          0
3  3  2017-02-01          1
4  3  2017-03-01          0
6  4  2017-01-01          1
9  4  2017-02-01          0
5  8  2017-04-01          0

太好了,谢谢你。我试图用.shift函数来实现这个功能,但它变得有点困难。以前没有使用此复制函数。谢谢你,太好了,谢谢你。我试图用.shift函数来实现这个功能,但它变得有点困难。以前没有使用此复制函数。谢谢你。