Python 将相应的列连接到数据帧
我有一个dataframe示例,如下所示。我想进行计算,然后将结果作为一个新列附加到当前数据帧Python 将相应的列连接到数据帧,python,python-2.7,pandas,Python,Python 2.7,Pandas,我有一个dataframe示例,如下所示。我想进行计算,然后将结果作为一个新列附加到当前数据帧 A, B # this is my df, a csv file 1, 2 3, 3 7, 6 13, 14 下面是我尝试过的一些代码 for i in range(0,len(df.index)+1,1): if len(df.index)-1 == i: df['C'] = str(df.iloc[i]['A'] / df.iloc[i]['B'])
A, B # this is my df, a csv file
1, 2
3, 3
7, 6
13, 14
下面是我尝试过的一些代码
for i in range(0,len(df.index)+1,1):
if len(df.index)-1 == i:
df['C'] = str(df.iloc[i]['A'] / df.iloc[i]['B'])
else:
df['C'] = str((df.iloc[i+1]['A'] - df.iloc[i]['A']) / (df.iloc[i+1]['B'] - df.iloc[i]['B'])) # I need string as dtype
df.to_csv(Out, index = False)
这只给出最终循环的结果,而不是取决于每次计算的相应结果
A B C
1 2 2
3 3 1.33
7 6 0.75
13 14 0.93 # It is the result I'd like to see.
有人知道怎么修改吗?提前谢谢 更新:-来自@root:
In [131]: df['C'] = (df.A.shift(-1).sub(df.A, fill_value=0) / df.B.shift(-1).sub(df.B, fill_value=0)).round(2).astype(str)
In [132]: df
Out[132]:
A B C
0 1 2 2.0
1 3 3 1.33
2 7 6 0.75
3 13 14 0.93
In [133]: df.dtypes
Out[133]:
A int64
B int64
C object
dtype: object
您可以这样做:
df['C'] = (df.A.shift(-1) - df.A) / (df.B.shift(-1) - df.B)
df.loc[df.index.max(), 'C'] = df.loc[df.index.max(), 'A'] / df.loc[df.index.max(), 'B']
df.round(2)
收益率:
In [118]: df.round(2)
Out[118]:
A B C
0 1 2 2.00
1 3 3 1.33
2 7 6 0.75
3 13 14 0.93
更新:-来自@root的更加优雅的解决方案(一行代码):
In [131]: df['C'] = (df.A.shift(-1).sub(df.A, fill_value=0) / df.B.shift(-1).sub(df.B, fill_value=0)).round(2).astype(str)
In [132]: df
Out[132]:
A B C
0 1 2 2.0
1 3 3 1.33
2 7 6 0.75
3 13 14 0.93
In [133]: df.dtypes
Out[133]:
A int64
B int64
C object
dtype: object
您可以这样做:
df['C'] = (df.A.shift(-1) - df.A) / (df.B.shift(-1) - df.B)
df.loc[df.index.max(), 'C'] = df.loc[df.index.max(), 'A'] / df.loc[df.index.max(), 'B']
df.round(2)
收益率:
In [118]: df.round(2)
Out[118]:
A B C
0 1 2 2.00
1 3 3 1.33
2 7 6 0.75
3 13 14 0.93
您可以使用
sub
而不是减号,并提供关键字参数fill_value=0
在一行中完成所有操作。e、 g.df.A.shift(-1).sub(df.A,fill_值=0)/(df.B.shift(-1).sub(df.B,fill_值=0)
@root,是的,的确-它更优雅了,谢谢!我更新了答案没有问题。我用fill\u value
得到了一个更粗糙的解决方案,但直到我看到了你的答案才看到了好的解决方案!你可以使用sub
而不是减号,并提供关键字参数fill\u value=0
,在一行中完成这一切。e、 g.df.A.shift(-1).sub(df.A,fill\u value=0)/(df.B.shift(-1).sub(df.B,fill\u value=0)
@root,是的,的确-它更优雅,谢谢!我更新了答案没有问题。我使用fill\u value
得到了一个更粗糙的解决方案,但直到看到你的答案才看到好的解决方案!