inp = [{'Name':'Jack', 'Twitter':'twitter.com/Jack', 'Stats': [{'Year': 2018, 'Followers': '5000'}, {'Year':2019, 'Followers': '6000'}]}, {'Name':'Bill','Twitter':'twitter.com/Twitter'}]
df = pd.DataFrame(inp)
假设我有一个像这样的 DataFrame:
| Name | Twitter | Stats |
|------|---------------------|---------------------------------------------------------------------------|
| Jack | twitter.com/Jack | [{'Year': 2018, 'Followers': '5000'}, {'Year': 2019, 'Followers': '6000'}] |
| Bill | twitter.com/Twitter | |
如何将统计信息拆分为多行,然后将字典拆分为多列?此外,如果有 NaN,则忽略该行。
期望的输出:
| Name | Twitter | Year | Followers |
|------|---------------------|------|-----------|
| Jack | twitter.com/Jack | 2018 | 5000 |
| Jack | twitter.com/Jack | 2019 | 6000 |
| Bill | twitter.com/Twitter | | |
这是我的解决方案:
clms = ['Name', 'Twitter', 'Year', 'Followers']
new_df = pd.DataFrame(columns=clms)
for idx, row in df.iterrows():
try:
for elt in row.Stats:
new_series = pd.Series([row.Name, row.Twitter, elt['Year'], elt['Followers']], index=clms)
new_df = new_df.append(new_series, ignore_index=True)
except TypeError:
new_series = pd.Series([row.Name, row.Twitter, np.NaN, np.NaN], index=clms)
new_df = new_df.append(new_series, ignore_index=True)
所以基本上,这可能不是超级高性能,但它会创建一个具有相应拆分值的新数据帧,如果数据帧中没有值,则为 NaN
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句