簡體   English   中英

使用 Pandas 進行探索性數據分析

[英]Exploratory Data Analysis with Pandas

如何使用 pandas 將連續數據(如每行顯示不同月份的任期列)分組到單獨列中顯示的類別

你在尋找這樣的東西嗎?:

import datetime

import pandas as pd

# Make fake data
dates = {"tenure": [datetime.date(2020, 1, 31), datetime.date(2020, 1, 24), datetime.date(2020, 5, 13),
                    datetime.date(2021, 5, 23), datetime.date(2022, 5, 5), datetime.date(2020, 3, 16),
                    datetime.date(2020, 5, 28), datetime.date(2020, 9, 23), datetime.date(2020, 12, 28),
                    datetime.date(2021, 10, 12)]}
df = pd.DataFrame(data=dates)
任期
2020-01-31
2020-01-24
2020-05-13
2021-05-23
2022-05-05
2020-03-16
2020-05-28
2020-09-23
2020-12-28
2021-10-12
# Make months to group by
df["tenure"] = pd.to_datetime(df.tenure)
df["month"] = df.tenure.dt.month_name()
任期
2020-01-31 00:00:00 一月
2020-01-24 00:00:00 一月
2020-05-13 00:00:00 可能
2021-05-23 00:00:00 可能
2022-05-05 00:00:00 可能
2020-03-16 00:00:00 行進
2020-05-28 00:00:00 可能
2020-09-23 00:00:00 九月
2020-12-28 00:00:00 十二月
2021-10-12 00:00:00 十月
# Group by months and show "different months for each row"
df = (df
      .sort_values("tenure")
      .groupby("month")["tenure"]
      .apply(lambda x: x.reset_index(drop=True))
      .unstack()
      .reset_index())
0 1 2 3
十二月 2020-12-28 00:00:00 鈉鹽 鈉鹽 鈉鹽
一月 2020-01-24 00:00:00 2020-01-31 00:00:00 鈉鹽 鈉鹽
行進 2020-03-16 00:00:00 鈉鹽 鈉鹽 鈉鹽
可能 2020-05-13 00:00:00 2020-05-28 00:00:00 2021-05-23 00:00:00 2022-05-05 00:00:00
十月 2021-10-12 00:00:00 鈉鹽 鈉鹽 鈉鹽
九月 2020-09-23 00:00:00 鈉鹽 鈉鹽 鈉鹽

或者可能是這樣的?:

# Group by months and show "different months for each row"
df = (df.sort_values("tenure")
        .groupby("month")["tenure"]
        .apply(lambda x: x.reset_index(drop=True))
        .unstack()
        .reset_index()
        .T)
df = df.rename(columns=df.iloc[0]).drop(df.index[0]).reset_index(drop=True)
十二月 一月 行進 可能 十月 九月
2020-12-28 00:00:00 2020-01-24 00:00:00 2020-03-16 00:00:00 2020-05-13 00:00:00 2021-10-12 00:00:00 2020-09-23 00:00:00
鈉鹽 2020-01-31 00:00:00 鈉鹽 2020-05-28 00:00:00 鈉鹽 鈉鹽
鈉鹽 鈉鹽 鈉鹽 2021-05-23 00:00:00 鈉鹽 鈉鹽
鈉鹽 鈉鹽 鈉鹽 2022-05-05 00:00:00 鈉鹽 鈉鹽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM