如何用随机字典值填充pandas数据帧列

时间:2017-11-23 23:09:20

标签: python pandas dictionary dataframe random

我是Pandas的新手,我想玩随机文字数据。我正在尝试向DataFrame df添加2个新列,每个列都由从字典中随机选择的键(newcol1)+值(newcol2)填充。

countries = {'Africa':'Ghana','Europe':'France','Europe':'Greece','Asia':'Vietnam','Europe':'Lithuania'}

我的df已经有2列了,我喜欢这样的话:

    Year Approved Continent    Country
0   2016      Yes    Africa      Ghana
1   2016      Yes    Europe  Lithuania
2   2017       No    Europe     Greece

我当然可以使用for或while循环填充df [' Continent']和df [' Country']但我感觉.apply()和np.random.choice可以为此提供更简单,更可爱的解决方案。

2 个答案:

答案 0 :(得分:7)

是的,你是对的。您可以使用np.random.choice + map

df

    Year Approved
0   2016      Yes
1   2016      Yes
2   2017       No

df['Continent'] = np.random.choice(list(countries), len(df))
df['Country'] = df['Continent'].map(countries)

df

    Year Approved Continent    Country
0   2016      Yes    Africa      Ghana
1   2016      Yes      Asia    Vietnam
2   2017       No    Europe  Lithuania

您可以从len(df)键列表中随机选择country个键,然后使用country字典作为映射器查找以前选择的键的国家/地区等效项。

对于替换的第二步,pd.Series.replace也有效:

df['Country'] = df.Continent.replace(countries)

df

    Year Approved Continent    Country
0   2016      Yes    Africa      Ghana
1   2016      Yes      Asia    Vietnam
2   2017       No    Europe  Lithuania

为了完整起见,您还可以使用apply + dict.get

df['Country'] = df.Continent.apply(countries.get)

df

    Year Approved Continent    Country
0   2016      Yes    Africa      Ghana
1   2016      Yes      Asia    Vietnam
2   2017       No    Europe  Lithuania

答案 1 :(得分:0)

您也可以尝试使用DataFrame.sample()

df.join(
    pd.DataFrame(list(countries.items()), columns=["continent", "country"])
    .sample(len(df), replace=True)
    .reset_index(drop=True)
)

如果您的大陆国家/地区地图已经是数据框,可以加快速度。

如果你使用的是Python 3.6,另一种方法是使用random.choices()

df.join(
    pd.DataFrame(choices([*countries.items()], k=len(df)), columns=["continent", "country"])
)

random.choices()numpy.random.choice()类似,只是您可以传递键值元组对列表,而numpy.random.choice()只接受1-D数组。