![](/img/trans.png)
[英]Set new column values in pandas DataFrame1 where DF2 column values match DF1 index
[英]Get index of column where consecutive values are zero in pandas df
我有一个 pandas dataframe 像下面的 Python
user_id 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03
0 5 20.0 0 0 38.0 45.0 54.0 83.0 107.0 129.0 146.0 174.0 136.0 33.0
1 7 5.0 13.0 26.0 27.0 19.0 13.0 7.0 14.0 21.0 17.0 13.0 5.0 5.0
2 14 0.0 7.0 25.0 22.0 60.0 13.0 1.0 25.0 49.0 16.0 6.0 0.0 0.0
3 16 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
我想知道第一个月(列)有两个连续列的值为0。例如:
user_id 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 first_month
0 5 20.0 0 0 38.0 45.0 54.0 83.0 107.0 129.0 146.0 174.0 136.0 33.0 2020-04
1 7 5.0 13.0 26.0 27.0 19.0 13.0 7.0 14.0 21.0 17.0 13.0 5.0 5.0 -
2 14 0.0 7.0 25.0 22.0 60.0 13.0 1.0 25.0 49.0 16.0 6.0 0.0 0.0 2021-02
3 16 0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 2020-05
谁能帮我?
您可以使用df.shift
on axis=1
执行此操作,然后使用df.where
检查any
条件
u = df.drop('user_id',1)
c = (u.eq(0)&u.shift(-1,axis=1).eq(0))
df['first_month'] = c.idxmax(1).where(c.any(1)) #c.idxmax(1).where(c.any(1),'-')
print(df)
user_id 2020-03 2020-04 2020-05 2020-06 2020-07 2020-08 2020-09 \
0 5 20.0 0.0 0.0 38.0 45.0 54.0 83.0
1 7 5.0 13.0 26.0 27.0 19.0 13.0 7.0
2 14 0.0 7.0 25.0 22.0 60.0 13.0 1.0
3 16 0.0 2.0 0.0 0.0 0.0 0.0 0.0
2020-10 2020-11 2020-12 2021-01 2021-02 2021-03 first_month
0 107.0 129.0 146.0 174.0 136.0 33.0 2020-04
1 14.0 21.0 17.0 13.0 5.0 5.0 NaN
2 25.0 49.0 16.0 6.0 0.0 0.0 2021-02
3 0.0 0.0 0.0 0.0 0.0 0.0 2020-05
您可以尝试shift
和idxmax
:
s = df.iloc[:,1:].eq(0)
s = (s + s.shift(-1, fill_value=0,axis=1)) == 2
df['first_month'] = np.where(s.any(1), s.idxmax(1), '-')
Output(只是np.where
部分):
array(['2020-04', '-', '2021-02', '2020-05'], dtype=object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.