Pandas 数据分析(六)随机数据处理

41. 合并两个Series生成一个DataFrame

np.random.seed(66)
s1 = pd.Series(np.random.rand(20))
s2 = pd.Series(np.random.randn(20))

df = pd.concat([s1, s2], axis=1)
df.columns = ["col1", "col2"]
print(df)

42. 使用多个条件复杂筛选DataFrame

print(df[(df["col2"] >= 0) & (df["col2"] <= 1)])

43. 根据现有列新增一个新的数据列

df["col3"] = df["col2"].map(lambda x: 1 if x>=0 else -1)
print(df)

44. 根据现有数据列新增截断数值数据列

df["col4"] = df["col2"].clip(-1.0, 1.0)
print(df)

45. 数据列最大和最小的5个数字

print(df["col2"].nlargest(5))
print()
print(df["col2"].nsmallest(5))

46. 计算数字的累积加和值

print(df.cumsum())

47. 计算一列数字的中位数

print(df["col2"].median())
print(df["col2"].quantile())

48. 使用query筛选数据

print(df[df["col2"] > 0])
print(df.query("col2 > 0"))

49. 将DF前几行转换成数据字典

print(df.head(5).to_dict())

50. 将df的前几行生成html

print(df.head(5).to_html())

51. 按列名筛选df使用loc方法

np.random.seed(66)
df = pd.DataFrame(np.random.rand(10, 4), columns=list("ABCD"))
print(df)

print(df.loc[df['C'] > 0.8])

52. 多条件组合筛选df

print(df[(df["C"] > 0.3) & (df["D"] < 0.7)])

53. for循环遍历df

for index, row in df.head(5).iterrows():
    print(row)

54. 指定单元格设置df的值

df.iloc[3, 1] = np.nan
df.loc[8, 'D'] = np.nan

print(df)

55. 移除df中数据值为空的行

df2 = df.dropna()
print(df2)

56. 重新设置索引列

df2 = df2.reset_index(drop=True)
print(df2)

57. 统计每个数据列的缺失值

print(df.isnull().sum())

58. 使用数字填充缺失值

df = df.fillna(0)
print(df)

59. 修改df列的前后顺序

df = df[["D", "A", "B", "C"]]
print(df)

60. 删除df的一列或多列

print(df.drop("D", axis=1))
print(df.drop(["C", "D"], axis=1))

课程参考链接:https://ke.qq.com/course/4000626#term_id=104152097

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容