熊猫dataframe中的F弦格式
假设“成员.xlsx”包括与成员的数据相对应的列,例如“ country”,“ name”,“ job”,“ age”,“ hobby”,“ hepth”,“ height”,“ stright”等。我能够要弄清楚如何提取成员的“名称”列,其县是美国,如下面使用熊猫。
import pandas as pd
df=pd.read_excel('f:/temporary/members.xlsx')
df1=df.loc[df['Country']=='US', ['Name']]
df1.to_excel('f:/temporary/US_Names.xlsx')
现在,我还想提取其他国家成员(例如,“希腊”,“印度”)的其他列(例如,“工作”,“年龄”和“爱好”)。我想的是使用F-string替换“我们”和“名称”,这与此相似(我知道'df1 ='也应该更改,但稍后让我处理...)。
for a in ['US','Greece','India']:
for b in ['Name','Job','Age','Hobby']:
df1=df.loc.[df['Country']=={a}, [{b}]]
但是在'df1 = df.loc中。[df ['country'] == {a},[{b}]]',我不知道应该在f-string格式化的位置放置'f'。即使不是F弦格式,任何方法都将起作用。提前致谢。
环境:Windows 10 64位,Python 3.10.4,Pandas 1.4.1
Let's say 'members.xlsx' include columns corresponding to the members' data such as 'Country', 'Name', 'Job', 'Age', 'Hobby', 'Height', 'Weight', etc. I was able to figure out how to extract 'Name' column of the members whose county is the US as below using pandas.
import pandas as pd
df=pd.read_excel('f:/temporary/members.xlsx')
df1=df.loc[df['Country']=='US', ['Name']]
df1.to_excel('f:/temporary/US_Names.xlsx')
Now, I want to extract other columns also (e.g., 'Job', 'Age', and 'Hobby') of the members in other countries (e.g., 'Greece', 'India'). What I imagine is to replace 'US' and 'Name' with other strings using f-string which is similar to this (I know that 'df1=' should also be changed but let me handle that later...).
for a in ['US','Greece','India']:
for b in ['Name','Job','Age','Hobby']:
df1=df.loc.[df['Country']=={a}, [{b}]]
But in 'df1=df.loc.[df['Country']=={a}, [{b}]]', I have no idea where 'f' should be placed for f-string formatting. Any methods would work even if that is not f-string formatting. Thanks in advance.
Environment: windows 10 64-bit, python 3.10.4, pandas 1.4.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用:
如果您不需要分开具有不同价值的国家的DF,请使用:
演示:
输出:
Use:
If you need not the df of a country with different values be separated, just use:
Demonstration:
Output: