【问题标题】:TypeError while creating a pandas dataframe创建熊猫数据框时出现类型错误
【发布时间】:2016-10-18 05:27:52
【问题描述】:

我使用 pandas 包编写了以下 python 代码。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import Series

csv = pd.read_csv('train.csv')
df_csv = pd.DataFrame(csv)

PassengerId = np.array(df_csv['PassengerId'])
Age = np.array(df_csv['Age'])
Pclass = np.array(df_csv['Pclass'])
Sex = np.array(df_csv['Sex'])

i = 0
while i < 891:
    if Sex[i] == 'male':
        Sex[i] = 0
        i = i + 1
    else:
        Sex[i] = 1
        i = i + 1
Sex = np.array(Sex)
new_df = pd.DataFrame[
    'PassengerId': Series(PassengerId),
    'Age': Series(Age),
    'Pclass': Series(Pclass),
    'Sex': Series(Sex)
]

print(new_df)

我正在尝试通过读取 csv 文件来创建数据框,将几列存储为 numpy 数组,然后替换一个数组的值。当我再次将这些数组合并为数据框时,出现以下错误

D:\Projects\Titanic>python python.py
Traceback (most recent call last):
  File "python.py", line 27, in <module>
    'Sex': Sex
TypeError: 'type' object is not subscriptable

请帮帮我。提前致谢

【问题讨论】:

  • 这是无效的:new_df = pd.DataFrame[ 'PassengerId': Series(PassengerId), 'Age': Series(Age), 'Pclass': Series(Pclass), 'Sex': Series(Sex) ] 它应该是圆括号 () 另外你应该传递一个字典 new_df = pd.DataFrame({ 'PassengerId': Series(PassengerId), 'Age': Series(Age), 'Pclass': Series(Pclass), 'Sex': Series(Sex) })
  • 谢谢!效果很好!!!

标签: python arrays numpy pandas


【解决方案1】:

尝试替换

new_df = pd.DataFrame[
  'PassengerId': Series(PassengerId),
  'Age': Series(Age),
  'Pclass': Series(Pclass),
  'Sex': Series(Sex)
]

new_df = pd.DataFrame({
  'PassengerId': Series(PassengerId),
  'Age': Series(Age),
  'Pclass': Series(Pclass),
  'Sex': Series(Sex)
})

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2017-02-14
    • 1970-01-01
    • 2021-11-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多