Python 在数据帧中打开文件内容时如何维护二进制数值
我有一个文本文件,它只是一个保存为csv的熊猫数据框。以下是该文件的内容:Python 在数据帧中打开文件内容时如何维护二进制数值,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个文本文件,它只是一个保存为csv的熊猫数据框。以下是该文件的内容: combination_output,total_true,frequency,priori-probability 000,0,275,0.0 001,0,25,0.0 010,16,16,1.0 011,14,14,1.0 100,0,0,0 101,0,44,0.0 110,0,0,0 111,247,247,1.0 我的问题很简单:给定包含0或1的三个数字的组合输出,我在上面的文件中搜索这个组合,并返回该文件最
combination_output,total_true,frequency,priori-probability
000,0,275,0.0
001,0,25,0.0
010,16,16,1.0
011,14,14,1.0
100,0,0,0
101,0,44,0.0
110,0,0,0
111,247,247,1.0
我的问题很简单:给定包含0或1的三个数字的组合输出,我在上面的文件中搜索这个组合,并返回该文件最后一列的先验概率。下面是我如何做到这一点的,因为我应该在该文件中搜索一个大的组合矩阵:
#open the file as a pandas dataframe
table=pd.read_csv("myfile.csv")
#I have a big matrix where its several lines contain one combination
# of 3 binary numbers that I
# should search in that pandas dataframe
# For each value, I search it in that dataframe
for index_combination in range(combination.shape[0]):
#I get the probability in that table where the combination of
#1 and 0s is the same I want to search
probability=table.loc[table['combination_output'] == combination[index_combination],'priori-probability']
然而,这是我打印它时得到的结果
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
result = method(y)
000
Series([], Name: priori-probability, dtype: float64)
似乎无法在该表中搜索诸如000之类的值。通过打印熊猫数据框,我得到以下结果:
combination_output total_true frequency priori-probability
0 0 0 275 0.0
1 1 0 25 0.0
2 10 16 16 1.0
3 11 14 14 1.0
4 100 0 0 0.0
5 101 0 44 0.0
6 110 0 0 0.0
7 111 247 247 1.0
如您所见,熊猫数据框显示的不是000,而是0;不是001,而是1;它显示的不是010,而是10,以此类推。如果我在该表中搜索000,它应该返回0,这是该组合的概率
如何让pandas读取二进制值,就像它们保存在我的文本文件中一样,顺便说一句,该文件以前也是pandas数据帧?您可以将它们读取为字符串数据类型:
table=pd.read_csv("myfile.csv", dtype={'combination_output': str})
这将以字符串而不是数字的形式读取组合
我假设你的组合矩阵中有字符串值