【问题标题】:A complex transformation of a data set in pandaspandas 中数据集的复杂转换
【发布时间】:2015-03-07 15:35:25
【问题描述】:

我有以下数据框:

dictionary = {'Year': [1985, 1985, 1986, 1986, 1987, 1987], 'Wteam' :[1, 2, 3, 4, 5, 6], 'lteam': [ 9, 10, 11, 12, 13, 14] }
pdf = pd.DataFrame(dictionary)

    Wteam   Year    lteam
0    1      1985    9
1    2      1985    10
2    3      1986    11
3    4      1986    12
4    5      1987    13
5    6      1987    14

我需要按以下格式创建一个新的数据框:

team values   predicted_value 
1985_1_9            1
1985_2_10           1
1986_3_11           1 
1986_4_12           1
1987_5_13           1
1987_6_13           1

我的新数据框的值应该采用这种格式“year_Wteam_lteam”。我如何在熊猫中做到这一点。预测值列始终为 1。

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    您可以执行以下操作:

    final = pd.DataFrame()
    final['team values'] = pdf['Year'].astype('str') + '_' + pdf['Wteam'].astype('str') + '_' + pdf['lteam'].astype('str')
    final['predicted_value'] = 1
    

    【讨论】:

    • 如果我想要数字作为整数而不是字符串怎么办?
    • @user3796494:用下划线连接整数是没有意义的。 1985_1_9 必须是一个字符串。
    【解决方案2】:

    不创建新数据框的一种方法是:

    In [15]: pdf['team values'] = pdf.apply(lambda row: str(row['Year'])+'_'+ str(row['Wteam'])+'_'+str(row['lteam']), axis=1)
    
    In [16]: pdf['predicted_value'] = 1
    
    In [17]: pdf.drop(['Wteam','Year','lteam'],axis=1,inplace=True)
    
    In [18]: print pdf.head()
      team values  predicted_value
    0    1985_1_9                1
    1   1985_2_10                1
    2   1986_3_11                1
    3   1986_4_12                1
    4   1987_5_13                1
    

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 1970-01-01
      • 2019-08-16
      • 2021-12-18
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多