dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987], 'Wteam' :[9, 10, 11, 4, 5, 6], 'lteam': [ 1, 2, 3, 12, 13, 14] }
pdf = pd.DataFrame(dictionary)
Wteam Year lteam
0 9 1985 1
1 10 1985 2
2 11 1986 3
3 4 1986 12
4 5 1987 13
5 6 1987 14
我需要在 pandas 中创建一个新的数据框,其中包含以下行和列
Season_value result
1985_1_9 0
1985_2_10 0
1985_3_11 0
1985_4_12 1
1985_5_13 1
1985_6_14 1
形成新表的逻辑如下:
我必须循环遍历 pdf
表中的每一行,然后如果 W_team 值大于 l_team,则我的新数据框
中的第一列值应为 ” year_lteam_wteam",结果值应为零。
如果 W_team 值小于 l_team,则我的新数据框
中的第一列应为 year_Wteam_lteam 并且结果列应为零。
推荐link
最佳答案
你可以
- 使用
np.where
将值分配给pdf['result']
基于一个条件。在np.where(cond, 0, 1)
,cond
是一个类似 bool 数组的。np.where
返回形状与cond
相同的新数组其值为 0,其中cond
为 True,且 1 其中cond
是假的。 - 使用
.min()
和.max()
重新订购Wteam
和lteam
。 - 构建
Season_value
列为 Mostafa Mahmoud showed .
import numpy as np
import pandas as pd
def tostr(series):
return series.astype(str)
dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987], 'Wteam' :[9, 10, 11, 4, 5, 6], 'lteam': [ 1, 2, 3, 12, 13, 14] }
pdf = pd.DataFrame(dictionary)
pdf['result'] = np.where(pdf['Wteam'] > pdf['lteam'], 0, 1)
pdf['min'] = pdf[['Wteam','lteam']].min(axis=1)
pdf['max'] = pdf[['Wteam','lteam']].max(axis=1)
pdf['Season_value'] = tostr(pdf['Year'])+'_'+tostr(pdf['min'])+'_'+tostr(pdf['max'])
print(pdf[['Season_value', 'result']])
产量
Season_value result
0 1985_1_9 0
1 1985_2_10 0
2 1986_3_11 0
3 1986_4_12 1
4 1987_5_13 1
5 1987_6_14 1
关于python - pandas 中的循环和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925583/