我想使用 Pandas和NumPy在Python中转换以下数据集(CSV):
表1(csv)
Ads, Impressions, Clicks
Ad_1, 11, 1
Ad_2, 10, 2
到
表2(csv)
Ad_1, Ad_2
0, 0
0, 0
0, 0
0, 1
0, 0
1, 0
0, 0
0, 0
0, 1
0, 0
0
表2的印象基本上是总行数,随机插入1(计数=点击次数)。
转换后的表格将使用机器学习的“最高可信度”算法对2个广告集进行点击率优化。请帮助将表1转换为表2。
谢谢!
答案 0 :(得分:1)
我认为这应该可以解决问题:
import pandas as pd
import numpy as np
from io import StringIO
TESTDATA = StringIO("""Ads,Impressions,Clicks
Ad_1, 11, 1
Ad_2, 10, 2
""")
table_1 = pd.read_csv(TESTDATA, sep=",")
def convert(row):
clicks_to_generate = row['Clicks']
array_len = row['Impressions']
ad = np.zeros(array_len)
ad[:clicks_to_generate] = 1
np.random.shuffle(ad) # you want it random
return ad
ads = table_1.apply(convert, axis=1)
series_list = [pd.Series(ad) for ad in ads]
table_2 = pd.DataFrame(series_list).T
table_2 = table_2.add_prefix('Ad_')
print(table_2)
Ad_0 Ad_1
0 0.0 0.0
1 1.0 0.0
2 0.0 1.0
3 0.0 1.0
4 0.0 0.0
5 0.0 0.0
6 0.0 0.0
7 0.0 0.0
8 0.0 0.0
9 0.0 0.0
10 0.0 NaN
table_2.to_csv('table_2.csv', index=False)