Pandas - 格式化数据帧行不起作用

时间:2018-06-08 05:45:02

标签: python python-3.x pandas formatting

我正在尝试格式化数据框的行,但没有成功。

我的数据框输出是:

                       X                              Y
443   cd2a9dd781c1396d4000ae05fcc3a0b00a5dc4f9     889.825    
111   ae3faf7ed08967e93d5f5ed6e10a5b256ec8c7fa     883.275    
221   601f669c760687b84ec57fe1eec213e26114a262     868.345   
631   80f54ce2aa2839e80cd5447cb369ec31f5e1fd47     867.545   

我希望输出格式如下:

{"X": "cd2a9dd781c1396d4000ae05fcc3a0b00a5dc4f9", "Y": 889.8}
{"X": "ae3faf7ed08967e93d5f5ed6e10a5b256ec8c7fa", "Y": 883.2}

我尝试过:

format = '{"X": "{}", "Y": {%.1f}}'.format
my_df.apply(lambda x: format(**x), 1)

my_df.style.format({'X': '{"X": "{}",', 'Y': '"Y": {%.1f}}'})

my_df.to_string(formatters={'X':'"X": "{}",'.format, 'Y':'"Y": {%.1f}'.format})

没有对我有用。最后一次尝试(to_string)返回以下错误:

  

文件“/usr/local/lib/python3.5/dist-packages/pandas/io/formats/format.py”,第1781行,在get_result中       fmt_values = self._format_strings()
    文件“/usr/local/lib/python3.5/dist-packages/pandas/io/formats/format.py”,第1961行,在_format_strings中       在self.values中返回[self.formatter(x)for x]     文件“/usr/local/lib/python3.5/dist-packages/pandas/io/formats/format.py”,第1961行,中
      在self.values中返回[self.formatter(x)for x]   KeyError:'%'

有任何建议/帮助吗?

2 个答案:

答案 0 :(得分:1)

对于我使用更改% to :工作的最后一个解决方案:

df = df.to_string(formatters={'X':'"X": "{}",'.format, 'Y':'"Y": {:.1f}'.format})
print (df)
                                                    X          Y
443  "X": "cd2a9dd781c1396d4000ae05fcc3a0b00a5dc4f9", "Y": 889.8
111  "X": "ae3faf7ed08967e93d5f5ed6e10a5b256ec8c7fa", "Y": 883.3
221  "X": "601f669c760687b84ec57fe1eec213e26114a262", "Y": 868.3
631  "X": "80f54ce2aa2839e80cd5447cb369ec31f5e1fd47", "Y": 867.5

如果需要新的格式化列,请使用列表理解:

df['new'] = ['"X": "{}", "Y": {:.1f}'.format(i, j) for i, j in zip(df['X'], df['Y'])]
print (df)
                                            X        Y  \
443  cd2a9dd781c1396d4000ae05fcc3a0b00a5dc4f9  889.825   
111  ae3faf7ed08967e93d5f5ed6e10a5b256ec8c7fa  883.275   
221  601f669c760687b84ec57fe1eec213e26114a262  868.345   
631  80f54ce2aa2839e80cd5447cb369ec31f5e1fd47  867.545   

                                                   new  
443  "X": "cd2a9dd781c1396d4000ae05fcc3a0b00a5dc4f9...  
111  "X": "ae3faf7ed08967e93d5f5ed6e10a5b256ec8c7fa...  
221  "X": "601f669c760687b84ec57fe1eec213e26114a262...  
631  "X": "80f54ce2aa2839e80cd5447cb369ec31f5e1fd47...  

答案 1 :(得分:0)

尝试

my_df.to_dict(orient='records')