1. df样本乱序
df = df.sample(frac=1)
2. 将某列内容展开
例如,csv文件如下
label tags
传统节日 清明节,春节,中秋节,国庆节
国家 美国,中国,日本
希望获取如下的df文件
label tags
传统节日 清明节
传统节日 春节
传统节日 中秋节
传统节日 国庆节
df_new = df.drop('tags', axis=1).join(df_tags['tags'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).rename('tags'))
3. 字符串转日期
若df中该列的格式不是日期的标准格式:%Y-%m-%d %H:%M:%S,需要进行格式转换
def format_time(s):
"""
若原始数据格式为:2020年3月4号 17:48:43
:param s:
:return:
"""
return datetime.datetime.strptime(tender_time,'%Y年%m月%d号 %H:%M:%S')
df['publish_time'] = df['publish_time'].apply(lambda x: format_time(x))
df['publish_time'] = pd.to_datetime(df['publish_time'])
df['year'] = df['publish_time'].dt.year
df['month'] = df['publish_time'].dt.month
4. group by 分组统计
将df按ID分组后,将每个ID包含的tax和price列进行求和,并转为字典
ID tax price
aa 1 3
aa 6 14
bb 4 6
cc 3 89
转换之后的结果
[{'tax': [{'aa': 7}, {'bb': 4}, {'cc': 3}]},
{'price': [{'aa': 17}, {'bb': 6}, {'cc': 89}]}]
tax_info_dict = df.groupby(by=['ID'])[['tax', 'price']].sum().to_dict('dict')
5.按行转为字典
ID tax price
aa 1 3
aa 6 14
bb 4 6
cc 3 89
转换之后的结果
[{'ID': 'aa', 'tax': 1, 'price': 3},
{'ID': 'aa', 'tax': 6, 'price': 14}, ...]
update_data = df_out.to_dict('records')
6. 按行转为list
ID tax price
aa 1 3
aa 6 14
bb 4 6
cc 3 89
转换之后的结果
[['aa', 1, 3],
['aa', 6, 14], ...]
data_list = df.values.tolist()