我正在使用熊猫中的数据框,并且某些列中的某些值具有Type mismatch.
Required:
kotlin.collections.HashMap<Class<in Throwable>, () → Unit> /* = java.util.HashMap<Class<in Throwable>, () → Unit> */
Found:
kotlin.collections.HashMap<Class<BadRequestError>, () → Unit> /* = java.util.HashMap<Class<BadRequestError>, () → Unit> */
值。当我尝试使用Seaborn在该列上运行视觉效果时,出现以下错误:
ValueError:无法将字符串转换为float:'*'
我知道哪些列具有*
值:
*
答案 0 :(得分:0)
您可以执行以下操作。在我的示例中,我将在数据帧df
中包含两列y
和z
,其中可能包含*
。
import pandas as pd
df = pd.DataFrame({
'x': [1, 2, 3, 4],
'y': [1, 4, '*', 16],
'z': [2, 3, 5, '*'],
})
df[(df['y'] != '*') & (df['z'] != '*')].head()
答案 1 :(得分:0)
您可以使用replace
功能。因为争论只是通过按照这种方案的字典{我不需要它:这正是我想要的}。
例如:
df = pd.DataFrame({"column1": ["a", "b", "a"]})
print(df)
column1
0 a
1 b
2 a
df["column1"].replace({"a": "x", "b": "y"}, inplace=True)
print(df)
column1
0 x
1 y
2 x
答案 2 :(得分:0)
添加to_numpy
可以提高性能。
# Example to reproduce solution
# We know that col_a and col_b contains '*'
df = pd.DataFrame(
{
"col_a": [1, 5, "*", 6, 8, "*"],
"col_b": ["*", 6, 8, "*", 2, 4],
"col_c": [1, 6, 8, 10, 2, 4],
}
)
df = df[(df["col_a"].to_numpy() != "*") & (df["col_b"].to_numpy() != "*")]
如果您不介意使用numpy
并且列数很大,则可以使用:
import numpy as np
def clean_asterisk(df, cols):
"""
Drop asterisk in know columns
Parameters:
-----------
df : pd.DataFrame
DataFrame we want to clean
cols : str or list of strings
List of known columns with asterisks
Returns:
--------
df : pd.DataFrame
DataFrame cleaned without asterisk
"""
if len(cols) == 0:
raise ValueError(
"Pass at least a list of one element or a string with one character"
)
if len(cols) == 1 or isinstance(cols, str):
try:
df = df[df[cols].to_numpy() != "*"]
return df
except KeyError:
print(f"Column {cols} must be in the DataFrame")
try:
df = df[np.bitwise_and.reduce([df[col] != "*" for col in cols])]
return df
except KeyError:
print(f"Column {cols} must be in the DataFrame")
df = clean_asterisk(df,["col_a","col_b"])
最后一种方法具有更高的可伸缩性,但对于小型示例而言太复杂了。