【问题标题】:Stating which columns are numerical values only and stating it in original data frame说明哪些列仅是数值并在原始数据框中说明
【发布时间】:2020-11-11 08:02:49
【问题描述】:

下面我有一个数据框,我也知道如何找出哪一列只是数值。但是,我无法弄清楚如何生成类似于我的 desired_results 的东西,它保留了原始列名,但删除了所有行,只为数字列声明“数字”,为其他列声明空白。

数据

df2 = pd.DataFrame({'column1' : ['1','2','3','4'],
      'column2' : ['a', 'b', 'c', 'd']})
df2['column1'] = df2['column1'].astype('int')

找出哪些列是数值的代码

list(df2.select_dtypes(include=[np.number]).columns.values)

想要的结果

desired_results = pd.DataFrame({'column1' : ['numerical'],
      'column2' : ['']})

【问题讨论】:

  • 具体问题是什么?您可以检索所有列名的列表,并且您有一个数字列列表,因此您可以像上一个 sn-p 中的字典一样创建字典来构建数据框?
  • 更多答案here

标签: python pandas


【解决方案1】:

您可以使用to_numeric尝试将所有转换为数值:

df2.apply(pd.to_numeric, errors='coerce').notnull().all()

输出:

column1     True
column2    False
dtype: bool

【讨论】:

    【解决方案2】:
    num_cols = list(df2.select_dtypes(include=[np.number]).columns.values)
    values = ["numerical" if c in num_cols else "" for c in df2.columns]
    # values: ['numerical', '']
    
    desired_result = pd.DataFrame(values).T
    desired_result.columns = df2.columns
    # desired_result:
    #      column1 column2
    # 0  numerical
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 2012-12-28
      • 2013-12-12
      相关资源
      最近更新 更多