如何在python中附加来自不同数据帧的数据?

2024-10-02 06:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有大约20个数据帧,所有的数据帧都有相同的列,我想把数据添加到空的数据帧中,但是当我使用我的代码时

感兴趣的\u频率

     UPC    CPC   freq
0   136.0   B64G    2
1   136.0   H01L    1
2   136.0   H02S    1
3   244.0   B64G    1
4   244.0   H02S    1
5   257.0   B64G    1
6   257.0   H01L    1
7   312.0   B64G    1
8   312.0   H02S    1

    list_of_lists = []
    max_freq = df_interested_freq[df_interested_freq['freq'] == df_interested_freq['freq'].max()]
    for row, cols in max_freq.iterrows():
        interested_freq = df_interested_freq[df_interested_freq['freq'] != 1]
        interested_freq 
        list_of_lists.append(interested_freq)

    list_of_lists

为附加第一个数据帧,然后更改代码中的名称,以希望它将附加更多数据

list_of_lists = []
    for row, cols in max_freq.iterrows():
        interested_freq_1 = df_interested_freq_1[df_interested_freq_1['freq'] != 1]
        interested_freq_1 
        list_of_lists.append(interested_freq_1)

    list_of_lists

但是第一个数据消失了,只显示最近添加的数据。我做错什么了吗?你知道吗


Tags: of数据代码dfformaxlistslist
2条回答

为什么在这里使用append?不是单子。一旦有了第一个数据帧(例如称为d1),请尝试:

new_df = df1
new_df = pd.concat([new_df, df2])

您可以对所有20个数据帧执行相同的操作。你知道吗

从现有数据帧创建新数据帧的一种方法是使用df.copy()Here is Detailed documentation

df.copy()在这里非常相关,因为在新的dataframe中更改数据子集将更改初始的dataframe,因此,您很有可能丢失实际的dataframe,因此您需要它。你知道吗

假设示例数据帧是df1

>>> df1
   col1  col2
1    11    12
2    21    22

解决方案,您可以使用数据框副本方法,该方法将继承数据。你知道吗

>>> df2 = df1.copy()
>>> df2
   col1  col2
1    11    12
2    21    22

如果您需要像df1一样创建新的数据帧(df2),但不希望在DF中插入值,那么您可以选择使用reindex_like()方法。你知道吗

>>> df2 = pd.DataFrame().reindex_like(df1)
# df2 = pd.DataFrame(data=np.nan,columns=df1.columns, index=df1.index)
>>> df2
   col1  col2
1   NaN   NaN
2   NaN   NaN

相关问题 更多 >

    热门问题