Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧字符串格式(访问给定列)_Python_String_Pandas_Formatting_String Formatting - Fatal编程技术网

Python 数据帧字符串格式(访问给定列)

Python 数据帧字符串格式(访问给定列),python,string,pandas,formatting,string-formatting,Python,String,Pandas,Formatting,String Formatting,我尝试使用新样式格式在给定/指定列显示条目: np.random.seed(1234) df = pd.DataFrame(np.random.randint(7, size=(2, 2)), columns=['a', 'b']) c = df.iloc[0, :] # get row number 0 print("Here is {one[0]} and {two}".format(one=c, two=c['b'])) # Ok 但我想这样做: print("Here is {one[

我尝试使用新样式格式在给定/指定列显示条目:

np.random.seed(1234)
df = pd.DataFrame(np.random.randint(7, size=(2, 2)), columns=['a', 'b'])
c = df.iloc[0, :] # get row number 0
print("Here is {one[0]} and {two}".format(one=c, two=c['b'])) # Ok
但我想这样做:

print("Here is {one['a']} and {two}".format(one=c, two=c['b'])) ## Unfortunately KeyError: "'a'"

有可能这样做吗?怎么做?

我想你可以在
one['a']
中删除
'

print("Here is {one[a]} and {two}".format(one=c, two=c['b']))
Here is 3 and 6

您可以使用
loc
获取列
a
的值

print("Here is {one} and {two}".format(one=c.loc['a'], two=c['b']))
Here is 3 and 6
你也可以这样做

df['sum'] = df.sum(axis=1)

n = 0  # Get the first row.    
>>> "{row[a]} and {row[b]} makes {row[sum]}".format(row=df.iloc[n, :])
'3 and 6 makes 9'

你为什么要按你的建议去做?你想达到什么目的?关键是直接指定一列的名称比记住第6列是我感兴趣的列更容易!整洁的我从未想过删除格式字符串中的额外引号!你好,亚历山大。谢谢,但不是,你的回答没有回答我的问题:这只是
two=c['b']
的一个变体,而我只想在格式字符串中指定正确的列。访问数据点类似,区别在于数据应该放在
format()
部分,应用于它的任何格式都应该放在括号中,例如{1:%.2f}。虽然技术上可能,但不应在字符串本身中指定数据。为什么不能在字符串本身中指定数据字段?您链接到的文档不符合此建议。我认为在字符串中指定数据字段的可能性甚至是新型格式最有趣的一点。您可以使用位置参数(例如
{0}、{2}
等)或命名参数(例如
{one}、{two}
等)。然后指定该数据的格式,例如
“{one:.2f}”和{two:%}“
。这是PEP 3101,详细解释了更改的合理性。我不建议放弃复合字段名。我提倡“简单比复杂好”、“漂亮比难看好”和“可读性计数”。