简体   繁体   English

使用 python 将每条记录分配给相应的列

[英]Using python assign each record to respective column

I have data frame with some records.我有一些记录的数据框。 I need to combine required records and assign to new variable and put it into the same dataframe.我需要合并所需的记录并分配给新变量并将其放入同一个 dataframe 中。

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)

Output: Output:

在此处输入图像描述

Expected Output:预期 Output:

         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'}] 

Use DataFrame.to_dict with orient='records' :使用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}

If need nested lists use:如果需要嵌套列表,请使用:

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}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python,我如何使用for循环显示来自每个表的记录,这些表显示了所有列和相应的列标题 - using python, how do i loop using a for loop to display the records from each table showing all the columns and the respective column headers 使用 python/pandas 为 A 列中的每个唯一记录获取 B 列中的唯一值 - Get unique values in column B for each unique record in column A using python/pandas Python:如何在每一列中为每行中的给定总数分配值 - Python: How to assign value in each column with a given total in each row 为列中的每个 numpy 元素运行相应的 function - Run respective function for each numpy element in column 使用 python pandas 将行值转换为列以将日期字段分配给每个新列 - Convert row values to columns to assign date field to each new column using python pandas 在 python 中使用不同的循环分配每个值 - Assign each value using different loops in python 如何使用python和cx_Oracle更新oracle表中的列并在每次记录更新后提交 - how to update column in a oracle table and commit after each record update by using python and cx_Oracle python:为每种条目编号 - python: Numbering each entry respective to the kind 我想选择一列每一行的前 4 个单词,并根据该值使用 python 为另一个新创建的列分配一个新值 - I want to to pick the first 4 words of each row of a column and based on the value assign a new value to another newly created column using python Pandas:根据相应行的时间范围在列中分配值(无标题) - Pandas: Assign value in column based on time range of the respective row (no header)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM