熊猫dataframe中的F弦格式

发布于 2025-01-20 22:55:57 字数 747 浏览 0 评论 0原文

假设“成员.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许仙没带伞 2025-01-27 22:55:57

使用:

for a in ['US','Greece','India']:
    for b in ['Name','Job','Age','Hobby']:
        df1=df.loc[df['Country']==a, b]

如果您不需要分开具有不同价值的国家的DF,请使用:

for a in ['US','Greece','India']:
   df1=df.loc[df['Country']==a, ['Name','Job','Age','Hobby']]

演示:

df=pd.DataFrame({'Name':['ali', 'reza'], 'Country':['Ir', 'Gr']})
a='Ir'
b='Name'
df.loc[df['Country']==a, b]

输出:

0    ali
Name: Name, dtype: object

Use:

for a in ['US','Greece','India']:
    for b in ['Name','Job','Age','Hobby']:
        df1=df.loc[df['Country']==a, b]

If you need not the df of a country with different values be separated, just use:

for a in ['US','Greece','India']:
   df1=df.loc[df['Country']==a, ['Name','Job','Age','Hobby']]

Demonstration:

df=pd.DataFrame({'Name':['ali', 'reza'], 'Country':['Ir', 'Gr']})
a='Ir'
b='Name'
df.loc[df['Country']==a, b]

Output:

0    ali
Name: Name, dtype: object
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文