给出一个熊猫数据框:
fruit_prices = [('apple', 5.99),
('orange', 4.99),
('pear', 6.99)]
labels = ['fruit', 'price']
fruit_prices = pd.DataFrame.from_records(datasets, columns=labels)
fruit_prices
fruit price
apple 5.99
orange 4.99
apple 6.99
我想添加一个新列,例如仅包含两个值,但是以一种方式,这些唯一值中的每个都会在原始数据帧中的每个现有行中出现。
day = ['wednesday', 'wednesday', 'thursday']
预期输出:
fruit price day
apple 5.99 wednesday
apple 5.99 thursday
orange 4.99 wednesday
orange 4.99 thursday
apple 6.99 wednesday
apple 6.99 thursday
我认为也许只有从新列/系列中获得唯一值后,我才能使用itertools:
from itertools import cycle
dates = cycle(['wednesday','thursday'])
但是我不确定如何将其分配回数据框(以允许复制现有行的方式),或者这是否可行。我还考虑过从该系列创建一个单列数据框并将其合并,但这似乎是circuit回的,而且我也不知道如何去做。
答案 0 :(得分:1)
我相信您需要cross join
:
day = ['wednesday', 'thursday']
df = fruit_prices.assign(A=1).merge(pd.DataFrame({'day':day,'A':1}), on='A', how='outer')
print (df)
fruit price A day
0 apple 5.99 1 wednesday
1 apple 5.99 1 thursday
2 orange 4.99 1 wednesday
3 orange 4.99 1 thursday
4 pear 6.99 1 wednesday
5 pear 6.99 1 thursday
答案 1 :(得分:1)
使用itertools.cycle
:
day = ['wednesday', 'wednesday', 'thursday']
#list(set(day)
#['wednesday', 'thursday']
from itertools import cycle, islice
df_new=pd.concat([df,df[::-1]],ignore_index=True)
df_new['day']=list(islice(cycle(list(set(day) )), len(df_new)))
print(df_new)
fruit price day
0 apple 5.99 wednesday
1 orange 4.99 thursday
2 apple 6.99 wednesday
3 apple 6.99 thursday
4 orange 4.99 wednesday
5 apple 5.99 thursday