1. 筛选
# 使用query方法过滤
filtered_df = df.query('column_name > value and other_column == "some_value"')
# 使用布尔索引选取'value'列不为NaN的行
df_cleaned = df[df['value'].notna()]
#sql筛选
from pandasql import sqldf
sql="""
select * from df where age=20
"""
df_new=sqldf(sql)
2.group by
计数
count_df=df[["airport","airline"]].groupby(["airport"]).size().reset_index(name='airline_count')
3. 函数
def infoGet(x,filed):
try:
if isinstance(x,str):
info=json.loads(x)
elif isinstance(x,dict):
info=x
else:
return "-3"
if filed in info.keys():
return info[filed]
else:
return "-1"
except:
return "-2"
df['displayname'] = df['info'].apply(lambda x: infoGet(x, "displayname"))
df['tag'] = df.apply(judgeStatus,axis=1)
#传入参数
df['new_info'] = df.apply(getNewPoiInfo,args=(info_dict,), axis=1)
4 dataframe 转dict
df.set_index("poi_id",inplace=True)
df_dict = df.to_dict(orient='index')
df_dict = {k: v for k, v in df_dict.items()}
5 csv
保存
df.to_csv("result.csv", index=True)
读取
dtypes = {
'column_name': 'str'
}
df = pd.read_csv('data.csv', engine='python', encoding='utf-8',dtype=dtypes)
6 遍历
new_lie_name="new_lie"
for index, row in df.iterrows():
df.at[index, new_lie_name] = ";;".join([str(item) for item in old_airline_set])
7 过滤空数据
import pandas as pd
value = pd.NA # 或者使用 float('nan') 来创建 NaN 值
if pd.isna(value):
print("The value is NaN")
else:
print("The value is not NaN")
8 某列list,打平
# 创建一个包含列表的DataFrame
data = {
'id': [1, 2, 3],
'tag':["w","e","t"],
'values': [[10, 20], [30, 40, 50],[10,90]]
}
df = pd.DataFrame(data)
print(data)
# 使用explode方法展平列表
df_exploded = df.explode('values')
# 查看展平后的DataFrame
print(df_exploded)
904




被折叠的 条评论
为什么被折叠?



