Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python DataFrame:使用字符串数据类型减去列_Python_Pandas_Dataframe - Fatal编程技术网

Python DataFrame:使用字符串数据类型减去列

Python DataFrame:使用字符串数据类型减去列,python,pandas,dataframe,Python,Pandas,Dataframe,如何减去包含字符串类型值的两列?没有值用“---”表示,结果中应为“---”。结果也应该是字符串类型的值 来源 df1 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['5', '---', '7']}) x y 0 'a' '5' 1 'b' '---' 2 'c' '7' df2 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['1', '2', '---']}) x

如何减去包含字符串类型值的两列?没有值用“---”表示,结果中应为“---”。结果也应该是字符串类型的值

来源

df1 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['5', '---', '7']})

    x   y
0   'a' '5'
1   'b' '---'
2   'c' '7'

df2 = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': ['1', '2', '---']})

    x    y
0   'a'  '1'
1   'b'  '2'
2   'c'  '---'
目标

df3 = df1 - df2

    x   y
0   'a' '4'
1   'b' '---'
2   'c' '---'
尝试:

df1.set_index('x').apply(lambda x: pd.to_numeric(x,errors='coerce')).sub(
      df2.set_index('x').apply(lambda x: pd.to_numeric(x,errors='coerce'))).fillna('--')\
                                                                .reset_index()


您可以使用
pd.to_numeric
将所有
'-'
替换为
NaNs
,也可以将所有值强制转换为
浮动

df1['y'] = pd.to_numeric(df1['y'], errors='coerce')
df2['y'] = pd.to_numeric(df2['y'], errors='coerce')
只需将两列相减,并将结果存储在
df1
中,例如:

df1['y'] = (df1['y'] - df2['y']).replace(np.nan,'---')

   x    y
0  a    4
1  b  ---
2  c  ---

使用
pd.to_numeric(…,errors='compresse')
生成数字,然后减去特定列,并使用
fillna('--')将其转换回字符串。astype(str)
的工作方式很有魅力。谢谢
df1['y'] = (df1['y'] - df2['y']).replace(np.nan,'---')

   x    y
0  a    4
1  b  ---
2  c  ---