python创建矩阵_for循环在python中创建一个矩阵

1586010002-jmsa.png

I am trying to study the probability of having a zero value in my data and I have developed a code that outputs the value of a column of data when the other is zero which is what I need. But having to do that for each column vs all other 28 of my 577by29 dataframe is difficult so I decided to create a for loop that does that for me where I have this:

import numpy as np

import pandas as pd

allchan = pd.read_csv('allchan.csv',delimiter = ' ')

allchanarray = np.array(allchan)

dfallchan = pd.DataFrame(allchanarray,range(1,578),dtype=float)

y = pd.DataFrame()

x = pd.DataFrame()

for n in range(0,29):

x[n] = dfallchan[(dfallchan[0]>0) & (dfallchan[n]==0)][0]

y[n] = x[n].count()

x.to_excel('n.xlsx', index=False, sheet_name='ValForOtherZero')

y.to_excel('v.xlsx', index=False, sheet_name='CountOfZeroVlas')

The problem that is that the loop for some reason goes properly through the lines:

x[n] = dfallchan[(dfallchan[0]>0) & (dfallchan[n]==0)][0]

y[n] = x[n].count()

but it repeats the value of n=6 for the second condition:

(dfallchan[n]==0)

the output of the code should return different values of the first channel as the zeros are randomly distributed in my input file, but my output is correct for the data until the the 6th column -as my columns(0-5) should be empty- where it repeats the output for all other columns!

output:

output 1

you can see that the code loops correctly as the output data frame has n=29 columns but not for the condition specified above.

Please help, Thanks!

解决方案

This will more efficient.

all_values = []

for n in range(0,29):

condition = (dfallchan[0]>0) & (dfallchan[n]==0)

count = condition.sum()

vals = dfallchan[condition][0].values

all_values.append(vals)

all_values_df = pd.DataFrame(all_values).transpose()

Here, I am first creating a list of lists and appending all the values to it. Then at the end I am creating the dataframe and transposing it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值