df = df.replace({None: "", np.nan: "", "\t": "", "\n": "", "\x08": ""}, regex=True)
df = df.applymap(lambda x: " ".join(x.split()) if isinstance(x, str) else x)
dataframe数据样本:
import pandas as pd
df = pd.DataFrame({'name':['苹果','梨','草莓','苹果'], 'price':[7,8,9,8], 'cnt':[3,4,5,4]})
name cnt price
0 苹果 3 7
1 梨 4 8
2 草莓 5 9
3 苹果 6 8
a = df.groupby('price').count()>1
price = a[a['cnt'] == True].index
repeat_df = df[df['price'].isin(price)]
flag = df.price.duplicated()
0 False
1 False
2 False
3 True
Name: price, dtype: bool
flag.any()结果为True (any等于对flag or判断)
flag.all()结果为False (all等于对flag and判断)
flag = df.duplicated()
判断方法同1
df.duplicated(subset = ['price','cnt'])
判断方法同1
4. 对dataframe数据数据去重
DataFrame.drop_duplicates(subset=None, keep='first', inplace=False)
示例:
df.drop_duplicats(subset = ['price','cnt'],keep='last',inplace=True)
drop_duplicats参数说明:
参数subset
subset用来指定特定的列,默认所有列
参数keep
keep可以为first和last,表示是选择最前一项还是最后一项保留,默认first
参数inplace
inplace是直接在原来数据上修改还是保留一个副本,默认为False
import csv
import pandas as pd
#
data = {'col1': ['Hello\nWorld', 'Line\nbreak"'], 'col2': [1, 2]}
df = pd.DataFrame(data)
print(df)
df.to_csv('data.csv', line_terminator='\n', quoting=csv.QUOTE_ALL, index=False, header=False)
df = pd.read_csv('data.csv', header=None)
print(df)
运行结果:
5、当csv文件入hive时,遇到空值需要在hive中显示为null值
CREATE TABLE my_table
(
id int comment '编号',
name string comment '名称',
money decimal(10, 2) comment '金钱'
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
NULL DEFINED AS ''
STORED AS TEXTFILE
TBLPROPERTIES ("serialization.null.format"='');
NULL DEFINED AS ''将空字符串视为NULL值,'serialization.null.format'=''则用于指定NULL值在数据文件中的表示方式。通过这种方式,我们可以同时使用NULL DEFINED AS ''和serialization.null.format=''来将NULL值和空字符串表示在Hive中的一致性。
也可以修改已存在的表,如下?
alter table my_table set serdeproperties('serialization.null.format' = '');