Pandas - 如何重复数据框n次,每次都添加一列?

4
如何在重复数据的同时为每个重复添加一个新列?
我已经尝试了多次,并成功将数据重复n次,但是我无法找到如何添加新列的方法。以下是我的初始温度数据框:
df1 = 
    temp
0   30
1   40
2   50
3   60

我可以使用以下代码将其复制n次:

df2 = pd.DataFrame(np.repeat(df.values,2,axis=0))

现在,我希望新的df有一个名为“city”的新列,并且每个新重复都会添加以下列表中指定的不同值 -

cities = ['Bangalore', 'Hyderabad'] //no. of cities will be same as n

expected output -
df2 = 
    temp city
0   30   Bangalore
1   40   Bangalore
2   50   Bangalore
3   60   Bangalore
4   30   Hyderabad
5   40   Hyderabad
6   50   Hyderabad
7   60   Hyderabad

如何获取此内容

3个回答

7

使用DataFrame.assignpd.concat

我们循环遍历cities列表中的每个城市,并将其作为新列assign。然后,我们使用concat将各个数据帧合并为一个最终的数据帧。

final = pd.concat([df1.assign(city=c) for c in cities], ignore_index=True)

输出

   temp       city
0    30  Bangalore
1    40  Bangalore
2    50  Bangalore
3    60  Bangalore
4    30  Hyderabad
5    40  Hyderabad
6    50  Hyderabad
7    60  Hyderabad

4
使用 numpy.tilenumpy.repeat:
import pandas as pd
import numpy as np

temps = [30, 40, 50, 60]
cities = ['Bangalore', 'Hyderabad']

temp = np.tile(temps, len(cities))
city = np.repeat(cities, len(temps))
df = pd.DataFrame({"temp": temp, "city": city})

输出:

    temp    city
0   30  Bangalore
1   40  Bangalore
2   50  Bangalore
3   60  Bangalore
4   30  Hyderabad
5   40  Hyderabad
6   50  Hyderabad
7   60  Hyderabad

这很不错,但为了实现这一点,我需要将我的临时值放入一个列表中。 - Visualisation App
我喜欢你的 numpy 方法,很不错! - help-ukraine-now

1

使用 pandas.MultiIndex.from_product

pd.MultiIndex.from_product([df['temp'], cities], names=['temp', 'city']) \
    .to_frame(index=False) \
    .sort_values('city')

    temp    city
0   30  Bangalore
2   40  Bangalore
4   50  Bangalore
6   60  Bangalore
1   30  Hyderabad
3   40  Hyderabad
5   50  Hyderabad
7   60  Hyderabad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接