【问题标题】:getting len() of the pandas df column with a whitespace [duplicate]获取带有空格的 pandas df 列的 len() [重复]
【发布时间】:2019-07-21 08:42:49
【问题描述】:

我有以下df:

df
   Site In Site Out Transmission Commodity     parameter         value unit
0      Mid    North         hvac      Elec           eff  9.000000e-01     
1      Mid    North         hvac      Elec      inv-cost  1.650000e+06     
2      Mid    North         hvac      Elec      fix-cost  0.000000e+00     
3      Mid    North         hvac      Elec      var-cost  0.000000e+00     
4      Mid    North         hvac      Elec      inst-cap  0.000000e+00     
5      Mid    North         hvac      Elec        cap-lo  0.000000e+00     
6      Mid    North         hvac      Elec        cap-up  1.500000e+15     
7      Mid    North         hvac      Elec          wacc  7.000000e-02     
8      Mid    North         hvac      Elec  depreciation  4.000000e+01     
9      Mid    South         hvac      Elec           eff  9.000000e-01
...     

当我遵循它时:

len(df.Transmission)
54

我如何获得'Site In''Site Out' 的len(),因为他们的名字中有空格,我找不到使用.column_name 的方法???

说实话,有几种方法可以获得长度,但在这种情况下有没有办法使用.column_name

以下不起作用:

len(df.Site In)
*** SyntaxError: invalid syntax
len(df.SiteIn)
*** AttributeError: 'DataFrame' object has no attribute 'SiteIn'
len(df.Site_In)
*** AttributeError: 'DataFrame' object has no attribute 'Site_In'
len(df.Site' 'In)
*** SyntaxError: invalid syntax

【问题讨论】:

  • df['Site In']
  • ofc 这会起作用 :) 但我正在寻找类似我在传输中给出的示例
  • 停止将列作为属性访问,这不起作用的事实加上其他原因应该告诉您停止
  • 取一列的长度有没有点。保证与len(df) 相同。如果您可能打算进行一些不同的计算,您应该表达出来。
  • 如果 tat 如此重要df=df.rename(columns={'Site In':'Site_In'}) 然后做len(df.Site_In)

标签: python pandas content-length


【解决方案1】:
  1. len(df['Site In'])len(df['Site Out'])
  2. 您可以通过分配 df['Site Out'].column.valuesdf['Site In'].column.values 来重命名列,消除空格,您的方法就可以了。
  3. 您也可以使用 df.iloc(1) 处理 df['Site In'] 或 df.iloc(2) 处理 df['Site Out']。

还有很多方法,但这些是最常见的。

【讨论】:

  • 将在 2 分钟内接受
  • 非常感谢,@oakca
猜你喜欢
  • 2018-01-03
  • 2020-12-29
  • 2020-06-24
  • 2017-05-05
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 2017-02-26
  • 2017-10-07
相关资源
最近更新 更多