![](/img/trans.png)
[英]python pandas for loop assign column based on which dataframe it came from
[英]Add a new column to a dataframe in which each row adopts a different value based on the title of the dataframe it came from
所以我有一個多個數據幀的列表,我將它們連接在一個大的 dataframe 中。 現在我想在最后一個大 dataframe 中添加一列,但我希望此列的值根據 dataframe 的名稱而改變,每一行首先屬於。 這是一個例子:
list_of_df = [march_01, march_02, march_03]
big_df = pd.concat([march_01, march_02, march_03], ignore_index=True)
big_df['new_column'] = # i want this column to adopt the value '01' for those rows that originally belong
# to the march_01 dataframe, the value '02' for those rows that originally belong
# to the march_02 dataframe, and so on.
單程:
import itertools as it
big_df["new_column"] = list(it.chain.from_iterable([f"{j}".zfill(2)]*len(df)
for j, df in enumerate(list_of_df, start=1)))
這將獲取每個 df 的長度並多次重復"0x"
部分。 chain
然后將它們粘合在一起。
另一種方式:
import numpy as np
lengths = list(map(len, list_of_df))
starting_points = [0, *np.cumsum(lengths)[:-1]]
big_df.loc[starting_points, "new_column"] = [f"{j}".zfill(2)
for j, _ in enumerate(list_of_df, start=1)]
big_df["new_column"].ffill(inplace=True)
這首先通過 df 的長度的累積總和確定大 df 中 df 的起點(丟棄最后一個的長度,因為它對其起點無關緊要,並為第一個添加 0)。 然后為這些點放置"0x"
,最后向前填充剩余的NaN
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.