熊猫追加行

时间:2021-04-14 14:54:04

标签: python pandas dataframe

我有一个数据框和一个列表,如下所示。

df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})

list = [1, 2, 3]

我想创建一个新列,其中包含该列中的每个列表项,具有相同的行,如下所示:


   x    month week
0  4      1     1
1  5      2     1
2  6      3     1
3  4      1     2
4  5      2     2
5  6      3     2
6  4      1     3
7  5      2     3
8  6      3     3

我尝试循环,例如,获取 df 并创建新列并将该结果附加到列表中,但我以仅包含最后创建的 df 的列表结束。

l = []
k = [1,2,3]
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
for i in range(0,len(k)):
    df['Semana'] = k[i]
    l.append(df)

帮助:((

2 个答案:

答案 0 :(得分:0)

注意:- 在继续解决方案之前。此查询已使用 list 数据类型的转换解决。

因此,我已将您的查询中提到的数据集打印出来。

# Import all Libraries
import pandas as pd

# Declaration of DataFrame and List
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
list = [1, 2, 3]

# Print Records of DataFrame
df
# Output of Above Code
    x   month
0   4   1
1   5   2
2   6   3

现在,根据我们想要的输出。我们可以看到 xmonth 列的重复。要实现此输出,请按照以下步骤操作:-

# 'pd.concat()' Function for Repeatation of Data 'len(list) times' or '3 times{in our case}' 
df = pd.concat([df]*len(list), ignore_index = True)

# Print Updated DataFrame
df
# Output of Above Code

    x   month
0   4   1
1   5   2
2   6   3
3   4   1
4   5   2
5   6   3
6   4   1
7   5   2
8   6   3

在这一步之后,我们就可以进行最后一步了。将 week 数据以重复格式附加到 df 中,与上述生成的结果相关。请按照以下步骤操作:-

# Conversion of 'list' to 'Series' Type 
week = pd.Series(list)

# Repeatation of 'week' data 'len(list) times' or '3 times {in our case}'
week = week.repeat(len(list))

# 'reset_index()' for Reseting Index
week = week.reset_index(drop = True)

# Conversion of 'Series' to 'DataFrame' Type 
week = pd.DataFrame(x)

# Print 'Week DataFrame' Records
week
# Output of Above Code

    0
0   1
1   1
2   1
3   2
4   2
5   2
6   3
7   3
8   3

现在,最后,将上面生成的 week 数据附加到 df 中以生成最终输出

# Append 'Week DataFrame" with "Main DataFrame" 
df["week"] = week

# Print Final DataFrame
df
# Final Output of Above Code

    x   month   week
0   4   1       1
1   5   2       1
2   6   3       1
3   4   1       2
4   5   2       2
5   6   3       2
6   4   1       3
7   5   2       3
8   6   3       3

希望这个解决方案会有所帮助。

答案 1 :(得分:0)

你可以通过 for 循环和 pd.concat 函数来做到这一点 -

import pandas as pd

df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})

list1 = [1, 2, 3]
new_df = pd.DataFrame()
for i in range(len(list1)):
    df['week'] = list1[i]
    new_df = pd.concat([new_df, df])

final_df = new_df.reset_index(drop=True)

输出 -

    x   month   week
0   4   1       1
1   5   2       1
2   6   3       1
3   4   1       2
4   5   2       2
5   6   3       2
6   4   1       3
7   5   2       3
8   6   3       3