【问题标题】:Using python assign each record to respective column使用python将每条记录分配给相应的列
【发布时间】:2022-01-26 10:45:31
【问题描述】:

我有一些记录的数据框。我需要合并所需的记录并分配给新变量并将其放入同一个数据框中。

import pandas as pd
df = pd.DataFrame({'temp_c': [17.0, 25.0]},
              index=['Portland', 'Berkeley'])
df = df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)
print(df)

输出:

预期输出:

         temp_c           temp_f             new_type
portland  17.0             62.6       [{'temp_c': '17.0', 'temp_f': '62.6'}]
Berkley   25.0             77.0       [{'temp_c': '25.0', 'temp_f': '77.0'}] 

【问题讨论】:

    标签: python python-3.x pandas dataframe python-2.7


    【解决方案1】:

    DataFrame.to_dictorient='records' 一起使用:

    df['new_type'] = df[['temp_c','temp_f']].to_dict(orient='records')
    print (df)
              temp_c  temp_f                          new_type
    Portland    17.0    62.6  {'temp_c': 17.0, 'temp_f': 62.6}
    Berkeley    25.0    77.0  {'temp_c': 25.0, 'temp_f': 77.0}
    

    如果需要嵌套列表,请使用:

    df['new_type'] = [[x] for x in df[['temp_c','temp_f']].to_dict(orient='records')]
    print (df)
              temp_c  temp_f                            new_type
    Portland    17.0    62.6  [{'temp_c': 17.0, 'temp_f': 62.6}]
    Berkeley    25.0    77.0  [{'temp_c': 25.0, 'temp_f': 77.0}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 2018-08-23
      • 2020-09-20
      • 2015-09-05
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多