我有三个关于调查响应的pandas数据框,它们看起来完全相同,但是是以不同的方式创建的:
import pandas as pd
df1 = pd.DataFrame([[1,2,3],[4,5,'hey'],[7,8,9]])
df2 = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
df2.loc[1,2] = 'hey'
df3 = pd.DataFrame(index=range(3), columns=range(3))
for i in range(3):
for j in range(3):
if (i,j) != (1,2):
df3.loc[i,j] = i*3 + j + 1
else:
df3.loc[i,j] = 'hey'
# df1, df2, df3 look the same as below
0 1 2
0 1 2 3
1 4 5 hey
2 7 8 9
现在,当我沿着列计算总和时,它们都给出了相同的结果。
sumcol1 = df1.sum()
sumcol2 = df2.sum()
sumcol3 = df3.sum()
# sumcol1, sumcol2, sumcol3 look the same as below
0 12
1 15
dtype: int64
然而,当我沿行求和时,
df3
的结果与 df1
和 df2
不同。此外,似乎当 axis=0 时,包含字符串的列的总和不会被计算,而当 axis=1 时,所有行的总和将被计算,跳过属于包含字符串元素的列的元素。
sumrow1 = df1.sum(axis=1)
sumrow2 = df2.sum(axis=1)
sumrow3 = df3.sum(axis=1)
#sumrow1
0 3
1 9
2 15
dtype: int64
#sumrow2
0 3
1 9
2 15
dtype: int64
#sumrow3
0 0.0
1 0.0
2 0.0
dtype: float64
我有三个问题需要解答。
为什么
sumcol1
和sumrow1
的行为不同?为什么
sumrow1
和sumrow3
的行为不同?是否有一种正确的方法可以获得与
sumrow1
相同的结果,但使用df3
?
补充:
Is there a smart way to add only the numerical values while keeping the strings?
My current workaround (thanks to jpp's kind answer):
df = pd.DataFrame([[1,2,3],[4,5,'hey'],[7,8,9]]) df_c = df.copy() for col in df.select_dtypes(['object']).columns: df_c[col] = pd.to_numeric(df_c[col], errors='coerce') df['sum'] = df_c.sum(axis=1) #result 0 1 2 sum 0 1 2 3 6.0 1 4 5 hey 9.0 2 7 8 9 24.0
func = sum
和np.sum
对df.apply(func,axis = 1)
进行操作,会发生什么? - smcidf1.info()
和df3.info()
显示col3上的数据类型不同,正如jpp所诊断的那样。因此,df1.equals(df3)
失败了。我想象中有一些其他的数据帧比较方法可以更详细地指出它们是不同的数据类型;更新:pandas.testing.assert_frame_equal(df1, df3)可以做到这一点。 - smci