python - pandas 中的循环和转换

标签 python python-2.7 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     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()重新订购 Wteamlteam
  • 构建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/

相关文章:

C# .NET 与托管 Python (CPython) 的互操作性 -> 有什么问题吗?

python - glob.iglob 在所有子目录中查找所有 .txt 文件会产生错误

javascript - 在本地运行 Flask。我想根据在 JavaScript 中生成的名称显示图像

Pandas groupby 聚合将多个函数应用于多个列

python - 时间为00 :00时Pandas读取excel返回类型对象

python - 如何用零分隔数据框的象限

python - 错误消息: 'chromedriver' executable needs to be PATH

python - 在抽象方法上实现 "after"装饰器

python - Flask:使用 url_for 提供没有前导斜杠的 Assets

arrays - 何时使用 '.flat', '.flatiter'或 '.flatten()'