Python 熊猫的循环与转化
我需要在pandas中创建一个新的数据框,其中包含以下行和列Python 熊猫的循环与转化,python,python-2.7,pandas,Python,Python 2.7,Pandas,我需要在pandas中创建一个新的数据框,其中包含以下行和列 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 19
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
形成新表格的逻辑如下:
我必须循环查看pdf
表中的每一行,然后如果W_team值大于l_team,则我的新数据框中的第一列值应为“year\u lteam\u wteam”,结果值应为零
如果W_team value的值小于l_team,则my新数据框中的第一列应为year\u Wteam\u lteam,结果列应为零
推荐信您可以
- 用于根据条件将值分配给
pdf['result']
。在np.where(cond,0,1)
中,cond
是一个类似布尔的数组np。其中
返回与cond
形状相同的新数组,该数组的值为0,其中cond
为真,而cond
为假
- 使用
.min()
和.max()
重新排序Wteam
和lteam
李>
- 将
季节值
列构建为
屈服
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']])
您是否被限制在数据帧中循环?换句话说,您是否有兴趣直接从字典计算相同的输出?另外,您在这两种情况下都写到结果值应该为零——您的意思是第二种情况下的结果值应该为一吗?@jedwards是的,我想要数据frane的输出。在第一种情况下它应该是零,在第二种情况下它应该是一。@jedwards-你能解释一下np.where在这个上下文中(在解决方案中)是如何工作的吗。那太好了。你能解释一下np.where在这种情况下是如何工作的吗。
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