因此,我有一个多个数据帧的列表,并将它们连接在一个大的数据帧中。现在,我想要向最后一个大型数据帧添加一列,但我希望该列的值根据每行首先所属的数据帧的名称而改变。这是一个示例:
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.
发布于 2021-03-16 18:27:24
一种方法:
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
。
https://stackoverflow.com/questions/66660909
复制相似问题