Python 创建数据帧时发生TypeError

Python 创建数据帧时发生TypeError,python,arrays,numpy,pandas,Python,Arrays,Numpy,Pandas,我已经使用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

我已经使用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)
导入matplotlib.pyplot作为plt
作为pd进口熊猫
将numpy作为np导入
从熊猫进口系列
csv=pd.read\u 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
当我<891时:
如果性别[i]=“男性”:
性别[i]=0
i=i+1
其他:
性别[i]=1
i=i+1
Sex=np.数组(Sex)
新建_df=pd.DataFrame[
“PassengerId”:系列(PassengerId),
“年龄”:系列(年龄),
“Pclass”:系列(Pclass),
《性别》:系列(性别)
]
打印(新文档)
我试图通过读取一个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
D:\Projects\Titanic>python.py
回溯(最近一次呼叫最后一次):
文件“python.py”,第27行,在
“性”:性
TypeError:“type”对象不可下标
请帮帮我。提前感谢

尝试更换

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)
]


这是无效的:
new_df=pd.DataFrame['PassengerId':Series(PassengerId),'Age':Series(Age),'Pclass':Series(Pclass),'Sex':Series(Sex)]
它应该是圆括号
()
另外,你应该传递一个dict
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)]
它应该是圆括号
()
另外,你应该传递一个dict
new_df=pd.DataFrame({'PassengerId':Series(PassengerId),'Age':Series(Age),'Pclass':Series(Pclass),'Sex':Series(Sex)})
谢谢!它工作得很好!!!