我有一个数据框。。。你知道吗
A B C D E F
0 2018-02-01 2 3 4 5 6
1 2018-02-02 6 7 8 4 2
2 2018-02-03 3 4 5 6 7
…我将其转换为numpy数组。。。你知道吗
[['2018-02-01' 2 3 4 5 6]
['2018-02-02' 6 7 8 4 2]
['2018-02-03' 3 4 5 6 7]]
我想做的是:
我的代码如下:
import pandas as pd
df = pd.DataFrame([
['2018-02-01', 1, 3, 6, 102, 8],
['2018-02-01', 2, 3, 4, 5, 6],
['2018-02-02', 6, 7, 8, 4, 2],
['2018-02-03', 3, 4, 5, 6, 7]
], columns=['A', 'B', 'C', 'D', 'E', 'F'])
print(df)
#--> Here only save Columns A,B,C
nparray = df.as_matrix()
print(nparray)
#--> Loop throug Columns and would like to have it looped over the Column A first
for i in nparray:
print(i)
#Using the Values in B and C columns for that loop
calc= [func(B,C)
for B, C in zip(nparray)]
更新: 我举了一个数字例子。你知道吗
A B C D E F
0 2018-02-01 1 3 6 102 8
1 2018-02-01 2 3 4 5 6
2 2018-02-02 6 7 8 4 2
3 2018-02-03 3 4 5 6 7
伪代码看起来像下面这样(它更像一个嵌套循环)
loop over date 2018-02-01:
calc = func(Column B + Column C) = 1+3 = 4
next row is the same date so:
calc += func(Column B + Column C) = 4 + 2+ 3 = 9
for date 2018-02-01 the result is 9 and can be stored e.g. in a csv file
loop over date 2018-02-02
calc = func(Column B + Column C) = 6+7 = 13
for date 2018-02-02 the result is 13 and can be stored e.g. in a csv file
loop over date 2018-02-03
calc = func(Column B + Column C) = 3+4 = 7
for date 2018-02-03 the result is 7 and can be stored e.g. in a csv file
等等
df[['A','B','C']].values
df[['B', 'C']].apply(func, axis=1)
在这里,
func
将一次接收一行,因此您可以这样定义它:你也可以这样做:
或者这个:
请注意,与其他“矢量化”方法相比,这种迭代代码无论是使用
itertuples
还是apply
都非常慢。但是如果你坚持使用循环,你可以,对于小数据也可以。你知道吗对于问题的第一部分,只需选择要使用的列:
问题的第二部分是多余的,遍历numpy数组与遍历数据帧没有区别,因为各个数据类型是相同的,在本例中是整数。你知道吗
因此使用:
相关问题 更多 >
编程相关推荐