python - 从序列中减去数据框(或其唯一的列)

标签 python pandas

我正在尝试从系列中减去一个数据框(只有一列)。

df['newcol'] = df['Col A'] - df.filter(regex="INT : Q1")

但是,我收到以下错误:

 Exception: Data must be 1-dimensional

df['Col A'] 成为一个系列。

df.filter(regex="INT : Q1") 成为数据帧

您能否建议解决此问题。

df['Col A']
Out[126]: 
0       0.000000e+00
1       0.000000e+00
2       0.000000e+00
3       0.000000e+00
4       0.000000e+00
5       0.000000e+00
6       1.046203e+05
7      -8.081900e+02
.............
 .......


df.filter(regex="INT : Q1")
Out[127]: 
Quarter_incomeGroup_Final  INT : Q1_2018
  0                           0.000000e+00
  1                           4.997991e+05
  2                           7.915359e+04
  3                           4.837797e+04 
       .............
      ..............

最佳答案

使用Series.rsub从右侧减去,但输出不是新列而是 DataFrame:

df = df.filter(regex="INT : Q1").rsub(df['Col A'], axis=0)

示例:

df = pd.DataFrame({'INT : Q1 1':[4,5,4,5,5,4],
                   'INT : Q1 2':[7,8,9,4,2,3],
                   'INT : Q1 3':[1,3,5,7,1,0],
                   'Col A':[5,3,6,9,2,4]})

print (df)
   INT : Q1 1  INT : Q1 2  INT : Q1 3  Col A
0           4           7           1      5
1           5           8           3      3
2           4           9           5      6
3           5           4           7      9
4           5           2           1      2
5           4           3           0      4

df = df.filter(regex="INT : Q1").rsub(df['Col A'], axis=0)
print (df)
   INT : Q1 1  INT : Q1 2  INT : Q1 3
0           1          -2           4
1          -2          -5           0
2           2          -3           1
3           4           5           2
4          -3           0           1
5           0           1           4

如果想要创建新列 - filter 可以返回一个或多个列,因此可能的解决方案是通过 iloc 选择第一列:

df['newcol'] = df.filter(regex="INT : Q1").rsub(df['Col A'], axis=0).iloc[:, 0]

关于python - 从序列中减去数据框(或其唯一的列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51038837/

相关文章:

Python 应用配置最佳实践

python - 在 pandas 数据框中获取几年内工作日某个小时的平均值

Python 请求获取一个应该正常工作的 URL 的错误页面

python - 无法在 Python 中 pickle Tensorflow 对象 - TypeError : can't pickle _thread. _local 对象

python - 删除 Pandas Dataframe 中的列表

python - 如何提取数据集中一分钟的每个数据点?

python - pandas-将系列添加到数据框会导致出现 NaN 值

pandas - 用新数据 append 一个 pandas 数据框

python - 分割pandas数据框的有效方法

python - 如何在 Python 2.7 中实现 GMRES 的 ILU 预处理器?