[英]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.