【问题标题】:How to append a column name to pandas.core.indexes.base.Index如何将列名附加到 pandas.core.indexes.base.Index
【发布时间】:2022-01-03 06:22:07
【问题描述】:

感谢您查看我的问题。我想将目标列添加到new_thing,我该怎么办。谢谢。

import pandas as pd
# reading data from csv
df = pd.read_csv('data.csv')
df.head()
# The csv format
# ID    cot1    num1    target  num2    cat3
# 0 123 Santa Elena 100 1   52.00   a
# 1 124 India   77  1   25.00   d
# 2 125 Ruanda  60  0   32.10   b
# 3 126 Lesoto  11  0   -11.00  h
# 4 127 Singapur    79  0   0.07    j

df.dtypes
# diffrent columns category(int,string)
# out
# ID          int64
# cot1       object
# num1        int64
# target      int64
# num2      float64
# cat3       object
# dtype: object

new_thing = df.select_dtypes(include = ['object']).columns

new_thing

# out 
# Index(['cot1', 'cat3'], dtype='object')
type(new_thing)
# out 
#pandas.core.indexes.base.Index
# I want to add target column to the new_thing
# I have tried the below but no success
new_thing.append(df.target)
# 
# TypeError: all inputs must be Index

如您所见,我无法将目标添加到 new_thing

【问题讨论】:

  • 请粘贴您的实际照片,而不是图片。

标签: pandas indexing append


【解决方案1】:

 这个error 是因为new_thing 存储类型 pandas.DataFrame.index(列)的值,如果您想将'target' 添加到new_thing,您必须这样做

new_thing = df.select_dtypes(include = ['object']).columns
new_thing.append(df.columns[df.columns.get_loc("target")])

要添加选择类型object 的列和行,您不应使用实例.columns

new_thing = df.select_dtypes(include = ['object'])
print(pd.concat([new_thing, df[['target']]]))

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多