Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 如何在同样有字符串的列数据框中只保留数字?_Python_String_Pandas_Dataframe - Fatal编程技术网

Python 如何在同样有字符串的列数据框中只保留数字?

Python 如何在同样有字符串的列数据框中只保留数字?,python,string,pandas,dataframe,Python,String,Pandas,Dataframe,我的数据框中有以下列: Column1 Column2 Column3 Column4 a 1 2 a 1 2 a c b 3 c d 3 2 1 b 4 2 1

我的数据框中有以下列:

Column1   Column2    Column3     Column4
a            1           2           a     
1            2           a           c
b            3           c           d
3            2           1           b
4            2           1           a
c            1           d           a
这些列的类型是
object
,我想将
Column1
Column2
Column3
转换为数值类型
int8
,同时保留
Column4
作为类型对象。为此,我曾尝试使用
pd.To_numeric(data.Column1)
(我计划在使用
Column2
Column3
后也这样做),但我得到了以下错误:

ValueError:无法分析位置0处的字符串“a”

这就是为什么会发生的原因。我想知道是否有任何方法可以让我摆脱由这3列中的字符串组成的行,因此在此之后,我将得到:

Column1    Column 2    Column 3   Column 4
3            2           1           b
4            2           1           a
有没有办法做到这一点?还是有其他方法可以让我这么做

编辑:我已签入该问题,但它没有解决我的问题,因为我的数据集中的列多于两列,其中一列我不想将其转换为数字。

使用替换,将非数字值替换为缺少的值,然后按删除
NaN
s行,最后转换为
integer
s:

df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).dropna().astype(int)
print (df)
   Column1  Column2  Column3
3        3        2        1
4        4        2        1
详细信息

print (df.apply(lambda x: pd.to_numeric(x,errors='coerce')))
   Column1  Column2  Column3
0      NaN      1.0      2.0
1      1.0      2.0      NaN
2      NaN      NaN      NaN
3      3.0      2.0      1.0
4      4.0      2.0      1.0
5      NaN      1.0      NaN
编辑:

另一种解决方案是使用以下方法检查是否缺少值:


使用
df[pd.to_numeric(df.Column1,errors='concurve').notnull()]
谢谢!如果我的一列是由字符串组成的,而我不想将其转换为数字,我该如何处理它?我对我的问题进行了编辑,以证明它是正确的。我想我不能在这种情况下应用lambda,对吗?@Marisa-更好的方法是过滤列以进行列表检查,答案已编辑。Mask将所有条目作为False返回给我。我选中了
df.Column2[0]
,它返回了我的字符串类型(“1”)。可能是因为我有字符串,所以一切都是这样吗?@Marisa-可能需要
mask=df[cols].apply(lambda x:pd.to_numeric(x.str.strip(“”),errors='concurve')).notnull().all(axis=1)
?仍然不起作用,数据集中的数字不在“”之间。我之前写它们只是为了强调它们是字符串这一事实。
cols = ['Column1','Column2','Column3']
#define columns for check numeric
mask = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce')).notnull().all(axis=1)
#filtering
df = df[mask]
#converting to integers
df[cols] = df[cols].astype(int)
print (df)
   Column1  Column2  Column3 Column4
3        3        2        1       b
4        4        2        1       a

print (df.dtypes)
Column1     int32
Column2     int32
Column3     int32
Column4    object
dtype: object