pandas 数据框字符串格式化(访问给定列)
pandas dataframe string formatting (access a given column)
我尝试使用新式格式在 given/specified 列显示条目:
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'
我尝试使用新式格式在 given/specified 列显示条目:
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'