将df1列1与df2中的所有列进行比较,返回df2的索引

时间:2016-12-16 06:22:33

标签: python pandas numpy

我是大熊猫的新手很可能忽略了一些东西,但我一直在寻找并且还没有找到任何有用的东西。

我想要做的就是这个。我有2个数据帧。 df1只有1列和未知行数。 df2也有未知的行数,每个索引的列数也是未知的。

Example:
df1:
0     1117454
1     1147637
2     1148945
3     1149662
4     1151543
5     1151545
6     1236268
7     1236671
8     1236673
...
300   1366962

df2:
                1        2        3        4        5        6        7  
8302813476  1375294  1375297  1375313  1375318  1375325  1375330  1375331   
8302813477  1317422  1363270  1363288  1363262     None     None     None   
8302813478  1187269  1187276  1149662  1147843  1147639  1236650  1236656

所以我想要的是检查df1列1 - n的所有df2值,如果与df1中的任何值匹配,则标记{{1}的索引如果是,那么它是假的。

2 个答案:

答案 0 :(得分:3)

我认为您可以使用isin来测试从Series df2创建的Seriesdf1从一列df3 = df2.stack().isin(df1.squeeze()).unstack() print (df3) 1 2 3 4 5 6 7 8302813476 False False False False False False False 8302813477 False False False False False False False 8302813478 False False True False False False False 创建的匹配由stack。最后重塑squeeze

True

然后找到unstack之前至少有一个a = df3.any(axis=1) print (a) 8302813476 False 8302813477 False 8302813478 True dtype: bool 的所有值:

print (a[a].index)
Int64Index([8302813478], dtype='int64')

最后any

squeeze

另一种解决方案是df1['col'].unique()使用df3 = df2.stack().isin(df1['col'].unique()).unstack() print (df3) 1 2 3 4 5 6 7 8302813476 False False False False False False False 8302813477 False False False False False False False 8302813478 False False True False False False False ,谢谢boolean indexing

squeeze

---

我更喜欢df1,但同样的输出很简单,只需选择df3 = df2.stack().isin(df1['col']).unstack() print (df3) 1 2 3 4 5 6 7 8302813476 False False False False False False False 8302813477 False False False False False False False 8302813478 False False True False False False False 列:

<html>

<?php
session_start();

if (empty($_SESSION['h_cost'])) {$_SESSION['h_cost'] = $_SESSION['cost'];}

if (isset($_SESSION['cost']) and $_SESSION['cost'] != '') {

require("system/config.php");

$ip = GetRealIp();

if (isset($_GET['pay'])) {

$expire_time = time() + 259200;
$discode = '';
$now = time();
$buy_id = "$now";

for ($n=0;$n<20;$n++) {
    $buy_id .= rand(1,9);
}

if (intval($_SESSION['h_cost']) < 100) {
$sql = "INSERT INTO $prefix"."buy_info (ip,email,name,phone,link,cost,expire,discode,product,buy_id,zarin_code,ok,date) VALUES ('" . $ip . "','" . $_GET['email'] . "','" . $_GET['name'] . "','" . $_GET['phone'] . "','" . $_SESSION['url'] . "','" . $_SESSION['h_cost'] . "','" . $expire_time . "','" . $discode . "','" . $_SESSION['title'] . "','" . $buy_id . "','N','" . "1" . "','" . date("Y/m/d") . "')";
$act = mysql_query($sql) or die(mysql_error());

// Remote Connect

mysql_close();

define("re_adress","***");
define("re_username","***");
define("re_password","***");
define("re_db_name","***");

$prefix = "mby_";

$con=mysql_connect(re_adress,re_username,re_password);

mysql_query("SET NAMES 'utf8'", $con);
mysql_query("SET CHARACTER SET 'utf8'", $con);
mysql_query("SET character_set_connection = 'utf8'", $con);
mysql_select_db(re_db_name,$con) or die (mysql_error());

$sql = "INSERT INTO $prefix"."buy_info (ip,email,name,phone,link,cost,expire,discode,product,buy_id,zarin_code,ok,date) VALUES ('" . $ip . "','" . $_GET['email'] . "','" . $_GET['name'] . "','" . $_GET['phone'] . "','" . $_SESSION['url'] . "','" . $_SESSION['h_cost'] . "','" . $expire_time . "','" . $discode . "','" . $_SESSION['title'] . "','" . $buy_id . "','N','" . "1" . "','" . date("Y/m/d") . "')";
$act = mysql_query($sql) or die(mysql_error());

$_SESSION['buy_id'] = $buy_id;
$_SESSION['email'] = $_GET['email'];
$_SESSION['h_cost'] = $_GET['h_cost'];
Header('Location: /payment-result.php');
exit();
}

// Zarrin pall part

$MerchantID = '***'; //Required
$Amount = $_SESSION['h_cost']; //Amount will be based on Toman - Required
$Description = $_SESSION['title']; // Required
$Email = $_GET['email']; // Optional
$Mobile = $_GET['phone']; // Optional
$CallbackURL = $site_adress.'/payment-result.php'; // Required


$client = new SoapClient('https://www.zarinpal.com/pg/services/WebGate/wsdl', ['encoding' => 'UTF-8']);

$result = $client->PaymentRequest(
[
'MerchantID' => $MerchantID,
'Amount' => $Amount,
'Description' => $Description,
'Email' => $Email,
'Mobile' => $Mobile,
'CallbackURL' => $CallbackURL,
]
);

//Redirect to URL You can do it also by creating a form
if ($result->Status == 100) {
$sql = "INSERT INTO $prefix"."buy_info (ip,email,name,phone,link,cost,expire,discode,product,buy_id,ok,date) VALUES ('" . $ip . "','" . $_GET['email'] . "','" . $_GET['name'] . "','" . $_GET['phone'] . "','" . $_SESSION['url'] . "','" . $_SESSION['h_cost'] . "','" . $expire_time . "','" . $discode . "','" . $_SESSION['title'] . "','" . $buy_id . "','" . "0" . "','" . date("Y/m/d") . "')";
$act = mysql_query($sql) or die(mysql_error());

// Remote Connect

mysql_close();

define("re_adress","***");
define("re_username","***");
define("re_password","***");
define("re_db_name","***");

$prefix = "mby_";

$con=mysql_connect(re_adress,re_username,re_password);

mysql_query("SET NAMES 'utf8'", $con);
mysql_query("SET CHARACTER SET 'utf8'", $con);
mysql_query("SET character_set_connection = 'utf8'", $con);
mysql_select_db(re_db_name,$con) or die (mysql_error());

$sql = "INSERT INTO $prefix"."buy_info (ip,email,name,phone,link,cost,expire,discode,product,buy_id,ok,date) VALUES ('" . $ip . "','" . $_GET['email'] . "','" . $_GET['name'] . "','" . $_GET['phone'] . "','" . $_SESSION['url'] . "','" . $_SESSION['h_cost'] . "','" . $expire_time . "','" . $discode . "','" . $_SESSION['title'] . "','" . $buy_id . "','" . "0" . "','" . date("Y/m/d") . "')";
$act = mysql_query($sql) or die(mysql_error());

mysql_close();

$_SESSION['buy_id'] = $buy_id;
$_SESSION['email'] = $_GET['email'];
Header('Location: https://www.zarinpal.com/pg/StartPay/'.$result->Authority);
//برای استفاده از زرین گیت باید ادرس به صورت زیر تغییر کند:
//Header('Location: https://www.zarinpal.com/pg/StartPay/'.$result->Authority.'/ZarinGate');
} else {
echo'ERR: '.$result->Status;
}

}
else
{
$_SESSION['h_cost'] = $_SESSION['cost'];
$_SESSION['discode'] = NULL;
}
}
else
{
//header("location: /404.php");
}
?>

<head>
    <title>سبد خرید</title>
    <meta   http-equiv="content-type"   content="text/html;charset=utf-8"  />
    <meta   http-equiv="Content-Language"  content="Fa">

    <!--FavIcon-->
    <link rel="icon" type="image/png" href="img/favicon.png">

    <link rel="stylesheet" href="css/cart.css" />
    <link rel='stylesheet' href='css/font-style.css' >
    <link rel="stylesheet" href="css/font-awesome.min.css" >
    <link rel="stylesheet" href="css/bootstrap.min.css" >
    <link rel="stylesheet" href="css/style.css" >
</head>

<body>

<div class="header-area">
            <div class="container">
                    <div class="row">
                            <div class="col-md-8">
                                    <div class="user-menu">
                                            <ul>
                                                    <li><a href="#"><i class="fa fa-user"></i>ورود</a></li>
                                                    <li><a href="#"><i class="fa fa-pencil-square-o"></i> ثبت نام</a></li>
                                                    <li><a href="#"><i class="fa fa-phone"></i>ارتباط با ما</a></li>
                                                    <li><a href="#"><i class="fa fa-briefcase"></i>همکاری</a></li>
                                            </ul>
                                    </div>
                            </div>
                            <div style="width: 300px;float: right;text-align: right;height: 38px;line-height: 38px;" class="col-md-9"><?php echo $psubtitle; ?>&nbsp;<i style="font-size: 10px;" class="fa fa-star"></i></div>
                    </div>
            </div>
</div> <!-- End header area -->

<section class="adjuster">
<a href="http://mobyar.com"><img src="img/logo.png" style="border-bottom: #999999 dashed 1px;position: absolute;top: 15px;left:10px;width: 200px;height: 95px;" alt="" /></a>
<b style="border-bottom: #999999 dashed 1px;font-weight: normal;position: absolute;width: 580px; height: 100px;line-height: 130px;text-align: center;font-size: 25px;top: 10px;" >فاکتور فروش خدمات موب یار</b>
<table>
    <td style="background: #5a88ca;color: #fff;font-weight: normal;" width="600">نام محصول</td><td style="background: #5a88ca;color: #fff;font-weight: normal;" width="200">قیمت</td><tr></tr>
    <td class="p_title"><?php echo $_SESSION['title'] ?></td><td><?php echo $_SESSION['cost'] ?> ت</td><tr></tr>
</table>
<form style="display: block" action="" id="pay_form" method="get">
<input type="text" name="discode" id="discode" class="discode_input" placeholder="کد تخفیف" />
<input type="button" name="discode_do" id="discode_do" class="discode_do" value="استفاده" /><img class="dd_w" src="img/w8.gif" alt="w8" />
<div class="total-cost">مبلغ قابل پرداخت : <i id="mqp" style="font-style: normal"><?php echo $_SESSION['h_cost'] ?></i> ت</div>
    <input name="name" placeholder="نام کامل" type="text" /><div class="cls"></div>
    <input name="email" id="email" placeholder="آدرس ایمیل*" type="email" /><div class="cls"></div>
    <input name="phone" style="    position: relative;top: 4px;" placeholder="شماره تماس" type="text" />
    <input type="submit" name="pay" class="pay" value="پرداخت">
</form>
<div class="discode_result">
    <div class="dr_c"></div>
    <b>کد تخفیف اعمال شد !</b>
    <br>
    <br>
    <i>مبلغ پرداختی شما شامل x % تخفیف شده است</i>
</div>
<div class="cls"></div>
</section>

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/cart.js"></script>

</body>

</html>

答案 1 :(得分:3)

作为一个有趣的numpy替代

l1 = df1.values.ravel()
l2 = df2.values.ravel()

pd.DataFrame(
    np.equal.outer(l1, l2).any(0).reshape(df2.values.shape),
    df2.index, df2.columns
)

或使用setlist和理解

l1 = set(df1.values.ravel().tolist())
l2 = df2.values.ravel().tolist()

pd.DataFrame(
    np.array([bool(l1.intersection([d])) for d in l2]).reshape(df2.values.shape),
    df2.index, df2.columns
)

enter image description here