[英]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_dict
和orient='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.