我想将DataFrame的值从str更改为int。 我写了代码,
import scipy as sp
import scipy.stats
import pandas as pd
import numpy as np
x = sp.stats.chi2_contingency(df)
print(x)
df变量具有类似
的DataFrame表A B C D
0 23 45 18 49
当我运行此代码时,Traceback说
x = sp.stats.chi2_contingency(df)
File "/Users/xxx/anaconda3/envs/py36/lib/python3.6/site-packages/scipy/stats/contingency.py", line 242, in chi2_contingency
if np.any(observed < 0):
TypeError: '<' not supported between instances of 'str' and 'int'
所以我写了代码
x = sp.stats.chi2_contingency(int(df))
TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是'DataFrame'错误。我的代码出了什么问题?我应该如何解决这个问题?
答案 0 :(得分:1)
似乎值是字符串,因此将它们转换为数字:
df = pd.DataFrame({'A': {0: '23'}, 'B': {0: '45'}, 'C': {0: '18'}, 'D': {0: '49'}})
print (df)
A B C D
0 23 45 18 49
x = sp.stats.chi2_contingency(df.astype(int))
print(x)
(0.0, 1.0, 0, array([[ 23., 45., 18., 49.]]))