繁体   English   中英

pandas 在添加新列时返回一个系列而不是 dataframe

[英]pandas returns a series instead of a dataframe while adding a new column

我正在尝试执行一个简单的操作,即从现有的 dataframe 创建一个新的 dataframe 并同时尝试添加一个新列。 但是,pandas 返回一个系列而不是 dataframe。

controls['DESC']=cells1['CEL_DESCRIPTION']

我收到以下错误: print(controls.info())

AttributeError: 'Series' object has no attribute 'info'

我使用此代码并且没有收到错误:

import pandas as pd

old = pd.DataFrame({'temp_c': [17.0, 25.0]},index=['Portland', 'Berkeley'])
print(old)

new = old.copy().assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)
print();print(new)

print();print(new.info())

output:

          temp_c
Portland    17.0
Berkeley    25.0


          temp_c  temp_f
Portland    17.0    62.6
Berkeley    25.0    77.0


<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, Portland to Berkeley
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   temp_c  2 non-null      float64
 1   temp_f  2 non-null      float64
dtypes: float64(2)
memory usage: 48.0+ bytes
None

已编辑

在编辑版本中,我编辑代码以添加带有空格的列名称,例如temp c而不是temp_ctemp f而不是temp_f ,如下所示:

import pandas as pd

old = pd.DataFrame({'temp c': [17.0, 25.0]},index=['Portland', 'Berkeley'])
print(old)

new = old.copy().assign(**{'temp f': (lambda x: x['temp c'] * 9 / 5 + 32)})

print();print(new)

print();print(new.info())

output:

          temp c
Portland    17.0
Berkeley    25.0

          temp c  temp f
Portland    17.0    62.6
Berkeley    25.0    77.0

<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, Portland to Berkeley
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   temp c  2 non-null      float64
 1   temp f  2 non-null      float64
dtypes: float64(2)
memory usage: 48.0+ bytes
None

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM