python - 从数据系列创建 DataFrame

标签 python pandas dataframe series data-analysis

我有一个数据系列,

df,
           primary
Buy        484
Sell       429
Blanks     130
FX Spot    108
Income     77
FX Forward 2

尝试创建一个包含 2 列的数据框。 第一列值应该是 df 的索引 第二列应具有 df 中的主要值

 by using,
 filter_df=pd.DataFrame({'contents':df.index, 'values':df.values})
 I get,
 Exception: Data must be 1-dimensional

最佳答案

使用reset_indexrename_axis对于新列名称:

filter_df = df.rename_axis('content').reset_index()

另一个使用重命名的解决方案:

filter_df = df.reset_index().rename(columns={'index':'content'})

对于构造函数中的 DataFrame,需要 df['primary'] 来选择列

filter_df=pd.DataFrame({'contents':df.index, 'values':df['primary'].values})

print (filter_df)
      content  primary
0         Buy      484
1        Sell      429
2      Blanks      130
3     FX Spot      108
4      Income       77
5  FX Forward        2

关于python - 从数据系列创建 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641149/

相关文章:

python - Pandas 识别两列具有相同字符串的行

r 使用带有 NA 的行来 reshape 数据以识别新列

python - Pandas Dataframe 将我的字典变成了字符串

python - Django - 自定义管理操作日志记录

python - 如何使用 Pandas 按日期和字符串 multiIndex 聚合数据,然后打印到 .csv?

python - ImportError : libtk8. 6.so: 无法打开共享对象文件: 没有那个文件或目录

python - Pandas _metadata of DataFrame 持久化错误

r - 在多列上应用 tidyr::separate

python - 存储句子中有趣的单词

python - 使用未知数量的参数调用 itertools.product