gpt4 book ai didi

python - 如何使用 python 列表理解/字典将每一列打印为唯一变量

转载 作者:行者123 更新时间:2023-11-28 19:53:47 24 4
gpt4 key购买 nike

假设我们有一个 csv

PROPERTY_ID,CLIENT_ID,FROM_YEAR
1,5,2015
2,6,2015
3,9,2015
4,9,2015

我试图将 CLIENT_ID、PROPERTY_ID、FROM_YEAR 的每个唯一组合传递到字典或列表中,因此我可以将每个“PROPERTY_ID、CLIENT_ID、FROM_YEAR”对放入 MySQL 查询中:

SELECT * FROM client_5 WHERE PROPERTY_ID = 1 and FROM_YEAR = 2015;

SELECT * FROM client_6 WHERE PROPERTY_ID = 2 and FROM_YEAR = 2015;

SELECT * FROM client_9 WHERE PROPERTY_ID = 3 and FROM_YEAR = 2015;

SELECT * FROM client_9 WHERE PROPERTY_ID = 4 and FROM_YEAR = 2015;

从变量的角度:

1st round:
$CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=5,1,2015

2nd round
$CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=6,2,2015

3rd round
$CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=9,3,2015

4th round
$CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=9,4,2015

我尝试使用列表理解:

df = pd.read_csv("test.csv")

df2=df.apply(tuple, 1).unique().tolist()

for CLIENT_ID in [x[0] for x in df2]:

CLIENT_ID=CLIENT_ID.astype('str')

print "SELECT * FROM client"+CLIENT_ID

for PROPERTY_CODE in [y[1] for y in df2]:

PROPERTY_CODE=PROPERTY_CODE.astype('str')

print "WHERE PROPERTY_ID = "+PROPERTY_CODE

它返回以下内容,这不是我们要找的:

SELECT * FROM client_5
WHERE FK_PROPERTY_ID = 1
WHERE FK_PROPERTY_ID = 2
WHERE FK_PROPERTY_ID = 3
WHERE FK_PROPERTY_ID = 4

谁能指教一下?谢谢。

最佳答案

我会使用格式

fstr = '$CLIENT_ID,$PROPERTY_ID,$FROM_YEAR={CLIENT_ID},{PROPERTY_ID},{FROM_YEAR}'
df.drop_duplicates().apply(lambda x: fstr.format(**x), 1)

0 $CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=5,1,2015
1 $CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=6,2,2015
2 $CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=9,3,2015
3 $CLIENT_ID,$PROPERTY_ID,$FROM_YEAR=9,4,2015
dtype: object

关于python - 如何使用 python 列表理解/字典将每一列打印为唯一变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42199116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com