2017-02-20 28 views
0

我正在使用topic_.set_value(each_topic, word, prob)更改熊猫数据框中单元的值。基本上,我初始化了一个具有某种形状的numpy数组,并将其转换为熊猫数据框。然后,我使用上面的代码遍历所有列和行来替换这些零。问题是单元的数量大约是50,000,每次我设置值pandas都会将数组打印到控制台。我想压制这种行为。有任何想法吗?将熊猫输出印刷到控制台

EDIT

我有两个dataframes一个是topic_是目标数据帧和tw也就是源数据帧。 topic_是一个由词矩阵组成的主题,每个单元存储单词在特定主题中出现的概率。我已使用numpy.zerostopic_数据帧初始化为零。所述tw dataframe-

print(tw) 
    topic_id          word_prob_pair 
0   0 [(customer, 0.061703717964), (team, 0.01724444... 
1   1 [(team, 0.0260560163563), (customer, 0.0247838... 
2   2 [(customer, 0.0171786268847), (footfall, 0.012... 
3   3 [(team, 0.0290787264225), (product, 0.01570401... 
4   4 [(team, 0.0197917953222), (data, 0.01343226630... 
5   5 [(customer, 0.0263740639141), (team, 0.0251677... 
6   6 [(customer, 0.0289764173735), (team, 0.0249938... 
7   7 [(client, 0.0265082412402), (want, 0.016477447... 
8   8 [(customer, 0.0524006965405), (team, 0.0322975... 
9   9 [(generic, 0.0373422774996), (product, 0.01834... 
10  10 [(customer, 0.0305256248248), (team, 0.0241559... 
11  11 [(customer, 0.0198707090364), (ad, 0.018516805... 
12  12 [(team, 0.0159852971954), (customer, 0.0124540... 
13  13 [(team, 0.033444510469), (store, 0.01961003290... 
14  14 [(team, 0.0344793243818), (customer, 0.0210975... 
15  15 [(team, 0.026416114692), (customer, 0.02041691... 
16  16 [(campaign, 0.0486186973667), (team, 0.0236024... 
17  17 [(customer, 0.0208270072145), (branch, 0.01757... 
18  18 [(team, 0.0280889397541), (customer, 0.0127932... 
19  19 [(team, 0.0297011415217), (customer, 0.0216007... 

topic_数据帧的样品是num_topics大小(这是20)number_of_unique_words(在数据帧tw

继是我使用来代替每个码在topic_数据帧值

for each_topic in range(num_topics): 
    a = tw['word_prob_pair'].iloc[each_topic] 
    for word, prob in a: 
     topic_.set_value(each_topic, word, prob) 
+2

我不明白 - 如果不使用'只打印''topic_.set_value(each_topic,word,prob)'为什么它打印?顺便说一句,为什么使用这种方法?这是非常缓慢的,如果检查[文档](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe)有很多更好的方法。你的数据来源是什么? 'Lists','numpy array'?你能解释更多吗? – jezrael

+0

@jezrael我按照http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe中给出的答案。根据答案,set_value的运行速度最快。我没有使用'print'。我用来替换'topic_'数据帧中的零的数据源来自另一个数据框。 源数据帧的行看起来像: '[(taret_df_col_1,值_1),(taret_df_col_2,_2),...,(taret_df_col_n,value_n)]' 我遍历所述源数据的每一行帧,然后在每个(列,值)对将它放在目标数据帧 –

+1

嗯,似乎必须有更好的方法。你能添加[最小的,完整的和可验证的例子](http://stackoverflow.com/help/mcve)作为输入数据样本和期望的输出吗? – jezrael

回答

1

只是输出重定向到变量:

>>> df.set_value(index=1,col=0,value=1) 
      0   1 
0 0.621660 -0.400869 
1 1.000000 1.585177 
2 0.962754 1.725027 
3 0.773112 -1.251182 
4 -1.688159 2.372140 
5 -0.203582 0.884673 
6 -0.618678 -0.850109 
>>> a=df.set_value(index=1,col=0,value=1) 
>>> 

至Init,DF它更好地使用:

pd.DataFrame(np.zeros_like(pd_n), index=pd_n.index, columns=pd_n.columns) 
1

如果您不希望创建一个变量(“A”在上面的建议),然后使用Python的一次性变量“_”。所以你的陈述变成:

_ = df.set_value(index=1,col=0,value=1)