[英]How to convert a two column csv file to a dictionary in python
I have the following csv:我有以下 csv:
Name1 Name2
JSMITH J Smith
ASMITH A Smith
How can I read it into a dictionary so that the output is如何将其读入字典以便输出为
dict = {'JSMITH':'J Smith', 'ASMITH': 'A Smith'}
I have used:我用过了:
df= pd.read_csv('data.csv')
data_dict = df.to_dict(orient='list')
but it gives me但它给了我
{'Name1': ['JSMITH','ASMITH'],'Name2': ['J Smith', 'A Smith']}
I am then hoping to use it in a map
function in pandas
such as:然后我希望在
pandas
的map
功能中使用它,例如:
df2['Name'] = df2['Name'].replace(data_dict, regex=True)
Any help would be much appreciated!任何帮助将非常感激!
Trick if you always have only two columns:如果您总是只有两列,请注意:
dict(df.itertuples(False,None))
Or make it a pandas.Series
and use to_dict
:或者使它成为
pandas.Series
并使用to_dict
:
df.set_index("Name1")["Name2"].to_dict()
Output:输出:
{'ASMITH': 'A Smith', 'JSMITH': 'J Smith'}
Note that if you need a mapper to a pd.Series.replace
, Series
works just as fine as a dict
.请注意,如果您需要一个映射到
pd.Series.replace
的映射器,则Series
与dict
一样pd.Series.replace
。
s = df.set_index("Name1")["Name2"]
df["Name1"].replace(s, regex=True)
0 J Smith
1 A Smith
Name: Name1, dtype: object
Which also means that you can remove to_dict
and cut some overhead:这也意味着您可以删除
to_dict
并减少一些开销:
large_df = df.sample(n=100000, replace=True)
%timeit large_df.set_index("Name1")["Name2"]
# 4.76 ms ± 1.09 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit large_df.set_index("Name1")["Name2"].to_dict()
# 20.2 ms ± 976 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
您可以使用zip
和dict
dict(zip(df.Name1, df.Name2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.