列的每一行的唯一值

2024-05-19 18:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框

Columns: []
Index: [(2, TOPPER, 1, Ahmad Anis), (3, t2, 1, Ahmad Anis), (3, t2, 3, Ahmad Anis)]

现在,我想把它送到Jinja,做一张桌子

from bs4 import BeautifulSoup
soup = BeautifulSoup(details.to_html(), features="lxml")
soup.find("tr").extract()

id = list(map(lambda a:a[0], details)) #list like [0,1,2,3]

html = str(soup)
return render_template('read_badge.html', tables=[html], id=id)

现在在金贾

{% for table,i_d in tables|zip(id)%}
   
    <form action="" method="post">
        
        <input type="submit" name='bid', value="{{i_d}}"> {{ table|safe }} </input>
        </form>

    {% endfor %}

我想将badge_id指定为badge_id列每行的值

enter image description here

对于第一行/索引,如果我们单击BADGE_ID,它应该发送一个值为2的post请求,如果我们单击next,它应该发送一个值为3的post请求

仅适用于第一列

如何做到这一点


Tags: badgeformidinputtableshtmltabledetails
2条回答

在创建表时,您可以将相同的类分配给每个td-like<td class="myclass">{{i_d}}</td>

将所有这些都保存在表单中,并将类添加到表单中,在javascript中,首先包括jquery

$(document).ready(function(){
$('.myclass').click(function(){
    $(".formclass").val($(this).text())
$('.formclass').trigger('submit')
}); });

这应该行得通

这个问题使得to_html()创建了HTML table,之后很难使用这个表

您应该在每个单元格中放置form或更好的链接<a href=" .../BADGE_ID">value</a>,但使用HTML table这是一个大问题

您可以直接将DataFrame发送到template,并使用模板中的for循环创建<table>

完整工作示例:

from flask import Flask, request, render_template_string
import pandas as pd
`

app = Flask(__name__)


data = [
    (2, 'TOPPER', 1, 'Ahmad Anis'),
    (3, 't2', 1, 'Ahmad Anis'),
    (3, 't2', 3, 'Ahmad Anis')
]
headers = ['BADGE_ID', 'BADGE_NAME', 'USER_ID', 'USER_NAME']

df = pd.DataFrame(data, columns=headers)
#df.set_index(['BADGE_ID', 'BADGE_NAME', 'USER_ID', 'USER_NAME'], inplace=True)


@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template_string('''<!DOCTYPE html>
<html>
<head>
<style>
table {background-color: #f88; margin: 0; padding: 0; border: none}
tbody tr:nth-child(even) {background-color: #fff}
tbody tr:nth-child(odd) {background-color: #eee}
th a, td a {display: block; text-align: center}
thead th, tbody th a, td a {padding: 5px 15px}
tr:hover a {background-color: #8f8}
</style>
</head>
<body>

<table border="0" cellspacing="0" cellpadding="0">

<thead>
<tr>
  <th>INDEX</th>
{% for name in headers %}
  <th>{{ name }}</th>
{% endfor %}
</t>
</thead>

<tbody>
{% for index, row in data.iterrows() %}
  <tr>
  <td><a href="/get/{{ row[0] }}">{{ index }}</a></td>
  {% for item in row %}
    <td><a href="/get/{{ row[0] }}">{{ item }}</a></td>
  {% endfor %}
  </tr>
{% endfor %}
</tbody>

</table>

</body>
</html>''', headers=headers, data=df)


@app.route('/get/<int:number>')
def get(number):
    result = df[ df['BADGE_ID'] == number]
    return render_template_string( f'<h1>BADGE_ID: {number}</h1>' + result.to_html() )


if __name__ == '__main__':
    #app.debug = True 
    app.run() 

另一种方法是将DataFrame中的所有数据转换为字符串

 <a href="/get/{BADGE_ID}">{item}</a>

然后使用to_html()

def create_link(row):
    BADGE_ID = row['BADGE_ID']
    return row.apply(lambda item: f'<a href="/get/{BADGE_ID}">{item}</a>')

df_with_links = df.apply(create_link, axis=1)

html = df_with_links.to_html(escape=False)

完整工作示例:

from flask import Flask, request, render_template_string
import pandas as pd

app = Flask(__name__)

data = [
    (2, 'TOPPER', 1, 'Ahmad Anis'),
    (3, 't2', 1, 'Ahmad Anis'),
    (3, 't2', 3, 'Ahmad Anis')
]
headers = ['BADGE_ID', 'BADGE_NAME', 'USER_ID', 'USER_NAME']

df = pd.DataFrame(data, columns=headers)
#df.set_index(['BADGE_ID', 'BADGE_NAME', 'USER_ID', 'USER_NAME'], inplace=True)

def create_link(row):
    BADGE_ID = row['BADGE_ID']
    return row.apply(lambda item: f'<a href="/get/{BADGE_ID}">{item}</a>')

@app.route('/', methods=['GET', 'POST'])
def index():

    df_with_links = df.apply(create_link, axis=1)
    # after `to_links`
    #df_with_links.set_index(['BADGE_ID', 'BADGE_NAME', 'USER_ID', 'USER_NAME'], inplace=True)

    html = df_with_links.to_html(escape=False, border='0" cellspacing="0" cellpadding="0')
    return render_template_string('''<!DOCTYPE html>
<html>
<head>
<style>
table {background-color: #f88; margin: 0; padding: 0; border: 0}
tbody tr:nth-child(even) {background-color: #fff}
tbody tr:nth-child(odd) {background-color: #eee}
th a, td a {display: block; text-align: center}
thead th, tbody th a, td a {padding: 5px 15px}
tr:hover a {background-color: #8f8}
</style>
</head>
<body>

{{ table | safe }}

</body>
</html>''', headers=headers, table=html)


@app.route('/get/<int:number>')
def get(number):
    result = df[ df['BADGE_ID'] == number]
    return render_template_string( f'<h1>BADGE_ID: {number}</h1>' + result.to_html() )

if __name__ == '__main__':
    #app.debug = True 
    app.run() 

相关问题 更多 >